gpt4 book ai didi

java - 可限时运行

转载 作者:搜寻专家 更新时间:2023-11-01 01:45:09 26 4
gpt4 key购买 nike

尝试构造一个必须在给定时间限制内结束的Runnable

目前我正在使用 java.util.Timer 来中断 Runnable 线程。

TimerRunnable 启动后立即启动。

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 !!");
}
}
}

但我怀疑这会导致 TimerRunnable 线程之间出现竞争条件:Runnable 即将完成,Timer 也在触发。

这会导致同时打印Finished !!Terminated !! 吗?如果是,如何避免?

更新:

它发生了:

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

最佳答案

Can this ever result in both Finished !! and Terminated !! being printed ?

是的。当打印“完成”消息时,计时器可能会在取消之前触发。

System.out.println("Finished !!");
// The timer can fire here.
timer.cancel();

如果发生这种情况,两条消息都将被打印出来。


要避免此问题,您可以使用同步。

synchronized (someObject) {
if (!finished) {
finished = true;
System.out.println("Finished !!");
timer.cancel();
}
}

在终结符中:

synchronized (someObject) {
if (!finished) {
finished = true;
task.interrupt();
System.out.println("Test Terminated !!");
}
}

这会阻止打印这两条消息。

关于java - 可限时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13309870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com