[豆知识] 多线程骑犀牛hello world

RednaxelaFX 2010-06-13
继续hello world。放个通过JSR 223使用JDK6自带的Rhino的例子。多线程,共享同一个ScriptEngine实例,但不共享Bindings,没干扰。顺便带个具名内部类的例子。

import java.util.*;
import javax.script.*;

public class TestRhino {
  public static void main(String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("javascript");
    
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("foo", 0);
    
    Bindings bindings1 = engine.createBindings();
    Bindings bindings2 = engine.createBindings();
    bindings1.putAll(variables);
    bindings2.putAll(variables);
    
    class MyTask implements Runnable {
      private String script;
      private Bindings bindings;
      public MyTask(String script, Bindings bindings) {
        this.script = script;
        this.bindings = bindings;
      }
      
      @Override
      public void run() {
        try {
          engine.eval(script, bindings);
        } catch (Exception e) { }
      }
    }
    
    Thread t1 = new Thread(new MyTask("for (var i = 0; i < 100000; i++) foo++", bindings1));
    Thread t2 = new Thread(new MyTask("for (var i = 0; i < 100000; i++) foo--", bindings2));
    
    t1.start();
    t2.start();
    
    t1.join();
    t2.join();
    
    System.out.println(bindings1.get("foo"));
    System.out.println(bindings2.get("foo"));
  }
}


D:\>javac TestRhino.java

D:\>java TestRhino
100000.0
-100000.0


注意那个MyTask编译出来的类文件名字是:TestRhino$1MyTask.class。
Global site tag (gtag.js) - Google Analytics