我正在代码中嵌入Groovy运行时,我希望能够中断它.我无法控制要运行的脚本.我读到有关groovy.transform.ThreadInterrupt的内容以处理线程中断,但是由于某些原因,下面的代码无法正常工作.实际上,它正在等待10000毫秒,而不是应该中断的1000毫秒.
有任何想法吗?谢谢.
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.transform.ThreadInterrupt;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer;
public class GroovyTest extends Thread {
private Binding binding;
private GroovyShell shell;
public GroovyTest() {
CompilerConfiguration compilerConfig = new CompilerConfiguration();
compilerConfig.addCompilationCustomizers(
new ASTTransformationCustomizer(ThreadInterrupt.class));
binding = new Binding();
shell = new GroovyShell(this.getClass().getClassLoader(), binding, compilerConfig);
}
@Override
public void run() {
System.out.println("Started");
shell.run("for(int i = 0; i < 10; i++) {sleep(1000)}", "test", new String[] {});
System.out.println("Finished");
}
public static void main(String args[]) throws InterruptedException {
GroovyTest test = new GroovyTest();
test.start();
System.out.println("Sleeping: " + System.currentTimeMillis());
Thread.sleep(1000);
System.out.println("Interrupting: " + System.currentTimeMillis());
test.interrupt();
test.join();
System.out.println("Interrupted?: " + System.currentTimeMillis());
}
}