Interpreting JavaScript in Java with Rhino: pausing/resuming scripts

前端 未结 3 1223
时光说笑
时光说笑 2020-12-30 03:44

I\'m using the javax.script.* package of the JDK. Specifically, I\'m using the JavaScript engine, which, from what I\'ve read, seems to be based on a Mozilla-developed Java

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 04:42

    You could use wait/notify:

    public final class Pause {
      private final Object lock = new Object();
    
      public void await() throws InterruptedException {
        synchronized (lock) {
          lock.wait();
        }
      }
    
      public void resumeAll() {
        synchronized (lock) {
          lock.notifyAll();
        }
      }
    }
    

    Usage:

    final Pause pause = new Pause();
    
    class Resumer implements Runnable {
      @Override public void run() {
        try {
          Thread.sleep(5000);
          pause.resumeAll();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    }
    new Thread(new Resumer()).start();
    
    SimpleBindings bindings = new SimpleBindings();
    bindings.put("pause", pause);
    String script = "print('Hello, ');\n"
                  + "pause.await();\n"
                  + "println('ECMAScript!');\n";
    new ScriptEngineManager().getEngineByName("ECMAScript")
                             .eval(script, bindings);
    

    This is a relatively simplistic solution as you don't mention any other constraints. wait() causes the thread to block, which would not be acceptable in all environments. There is also no easy way to identify what threads are waiting on the Pause instance if you want to run scripts concurrently.

    Note: the InterruptedException on await() should be handled either by the caller or by doing something more sensible in await().

提交回复
热议问题