2011-08-12 7 views
3

私は自分のコードにGroovyランタイムを組み込みたいので、中断する機能があります。私は実行しようとしているスクリプトを制御できません。スレッドの中断を処理するgroovy.transform.ThreadInterruptについて読んでいますが、何らかの理由でこのコードが意図したとおりに動作していません。それは実際には中断されるべき1000の代わりに10000ミリ秒を待っています。Groovyスクリプトの実行を中止する

アイデア?ありがとうございました。

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()); 
    } 
} 

答えて

4

私自身の質問に答える。 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; 
     } 
    } 
} 
関連する問題