当关联的Runnable执行空方法时,为什么线程卡在runnable中

时间:2019-03-18 17:21:05

标签: java multithreading runnable synchronized

在停止条件为真之前,我有一个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
    }
}

我可以使此代码终止

  • 以“调试”模式运行并将断点设置为 WorkerExecutor
  • 中的 run()中的 this.worker.execute()
  • 例如 execute 方法
  • 中的System.out.println()
  • 同步访问已停止的变量

我的问题是:为什么这个初始代码永远不会终止?

0 个答案:

没有答案