试图构建一个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