在停止条件为真之前,我有一个Runnable正在执行没有主体的对象的方法的情况。除此之外,它基本上什么也不做。问题是,执行此Runnable的线程永远保持运行状态。
对于此示例,我将在5秒钟的睡眠后在main方法中设置停止条件。
public class Main {
public static void main(String... args) {
WorkerExecutor workerExecutor = new WorkerExecutor();
new Thread(workerExecutor, "WorkerExecutorThread").start();
try {
Thread.currentThread().sleep(5000);
workerExecutor.setStopped(true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class WorkerExecutor implements Runnable {
private boolean stopped = false;
private Worker worker;
public WorkerExecutor() {
this.worker = new Worker();
}
public void run() {
while (!this.isStopped()) {
this.worker.execute();
// any statement here or within execute makes it work
}
}
// synchronizing this will do the trick
public void setStopped(boolean stopped) {
this.stopped = stopped;
}
// synchronizing this will do the trick
public boolean isStopped() {
return stopped;
}
}
public class Worker {
public void execute() {
// Doing a System.out.printn here will do the trick
}
}
我可以使此代码终止
我的问题是:为什么这个初始代码永远不会终止?