我有一段代码:
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();
}
}
发布于 2021-11-15 13:10:51
您需要不同的工具才能使其工作。您不能要求AtomicBoolean
等待它的值发生变化,但这正是您想要做的,所以您使用了错误的工具。
例如,更好的工具应该是j.u.c.Lock
变体、latch或类似工具。或者,如果您想使用java的内置原语,wait()
和notify()
synchronized (close) {
while (!close.get()) {
close.wait();
}
}
无论您在何处更改该AtomicBoolean:
synchronized (close) {
close.set(false);
close.notifyAll();
}
线程化很棘手,因为即使您编写了相当广泛的单元测试,您所犯的任何错误也不会(容易)被发现;实际行为取决于操作系统、硬件、VM版本和月相。
https://stackoverflow.com/questions/69974804
复制相似问题