微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-停止执行Groovy脚本

我正在代码中嵌入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());
    }
}

解决方法:

回答我自己的问题.
Groovy的静态方法sleep不会中断,即使您尝试没有闭包也是如此.
如果你问我,很奇怪的认设置.
推荐方式是调用Thread.sleep(ms)

private static void sleepImpl(long millis, Closure closure) {
    long start = System.currentTimeMillis();
    long rest = millis;
    long current;
    while (rest > 0) {
        try {
            Thread.sleep(rest);
            rest = 0;
        } catch (InterruptedException e) {
            if (closure != null) {
                if (DefaultTypeTransformation.castToBoolean(closure.call(e))) {
                    return;
                }
            }
            current = System.currentTimeMillis(); // compensate for closure's time
            rest = millis + start - current;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐