Why does this simple threaded program get stuck?

流过昼夜 提交于 2019-12-05 20:28:27

This is because your boolean is not volatile, therefore Threads are allowed to cache copies of it and never update them. I would recommend an AtomicBoolean - that will prevent any issues you may have.

public static void main(String args[]) {
    final AtomicBoolean done = new AtomicBoolean(false);
    new Thread() {
        public void run() {
            done.set(true);
        }
    }.start();
    while (!done.get());
    System.out.println("bye");
}

By the time the main program's while loop is reached (which is also a Thread), the new Thread might be finishing its run() where done flag is set to true. Just to confirm this, you can add a sleep in the run() before done is set to true and then see if your bye is displayed on other machine also. Hope this would help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!