在下面的代码中,我有一个javascript运行在与主要一个单独的线程中.该脚本是一个无限循环,因此它需要以某种方式终止.怎么样?
在脚本开始运行后调用.cancel()不起作用.但是如果我在线程初始化之后调用.cancel(),它将终止它(注释掉的行).
package testscriptterminate;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.Timer;
import java.util.TimerTask;
public class TestScriptTerminate extends TimerTask{
private ExecutorService threads;
private Future runScript;
private Timer t;
public TestScriptTerminate(){
t = new Timer();
t.schedule(this, 6000); //let the script run for a while before attempt to cancel
threads = Executors.newFixedThreadPool(1);
runScript = threads.submit(new ScriptExec());
//runScript.cancel(true); //will cancel here, before the script had a change to run, but useless, i want to cancel at any …Run Code Online (Sandbox Code Playgroud)