試圖構建Runnable
即必須在給定的時間限制內結束。可運行時間限制
當前我正在使用java.util.Timer
中斷Runnable
線程。
Timer
在Runnable
開始後立即開始。
import java.util.Timer;
import java.util.TimerTask;
public class test {
Thread task;
Timer timer;
public void start(){
task = new Thread(new worker());
timer = new Timer("timer",true);
task.start();
timer.schedule(new Terminator(),1000*2);
}
class worker implements Runnable{
@Override
public void run() {
for (int i = 0 ; i < 2; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Test Interrupted !!");
return;
}
}
System.out.println("Test Finished !!");
timer.cancel();
}
}
class Terminator extends TimerTask{
@Override
public void run() {
task.interrupt();
System.out.println("Test Terminated !!");
}
}
}
但我懷疑這會導致競爭條件Timer
和Runnable
線程之間: Runnable
即將完成,並Timer
也燒成。
這可以導致這兩個成品!!和終止!正在打印?如果是這樣,如何避免它?
更新:
它發生:
11-09 21:14:40.741: INFO/System.out(31442): Test Finished !! 18
11-09 21:14:40.751: INFO/System.out(31442): Test Terminated !! 18
11-09 21:14:40.751: INFO/System.out(31442): Test Finished !! 19
11-09 21:14:40.751: INFO/System.out(31442): Test Terminated !! 19
不回答你的問題,但是看看['TimeLimiter'(HTTP://docs.guava-libraries .googlecode.com/git/javadoc/com/google/common/util/concurrent/TimeLimiter.html)[tag:guava] –
@TomaszNurkiewicz謝謝。 –