我有一段代码:
public void foo(AtomicBoolean close){
new Thread(() -> {
try{
System.out.println("foo started");
while(!close.get()){
System.out.print("working");
//peace of code for execution.
//wait 1 second before re-execute the same thing.
//warning: Call to 'Thread.sleep()' in a loop, probably busy-waiting
try{ Thread.sleep(1_000); /*1sec*/ }catch(Exception ignored){}
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("foo stopped");
}, "fooThread").start();
}
代码可以工作,但我想摆脱那个警告,并且我不知道如何重写这段代码。
close
只是为了知道线程什么时候应该停止。
发布于 2021-11-15 16:22:39
我就是这么写的。您不一定需要这个类,它只是很好地封装了执行器和任务。
除了scheduleWithFixedDelay
之外,还有scheduleAtFixedRate
。不同之处在于explained here。我选择了最接近您的代码的代码。
class FooService
{
private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
private volatile ScheduledFuture<?> task;
public void start() {
if (task != null) {
throw new RuntimeException("Already started");
}
task = executor.scheduleWithFixedDelay(() -> {
System.out.println("working");
// piece of code for execution.
}, 0, 1, TimeUnit.SECONDS);
}
public void stop() {
task.cancel(true);
executor.shutdown();
}
}
https://stackoverflow.com/questions/69974804
复制相似问题