简体   繁体   English

为什么休眠主线程会更改Java中正在运行的其他线程的行为?

[英]Why sleeping the main Thread changes behaviour of the running other Thread in Java?

Here is my code: 这是我的代码:

/* User: koray@tugay.biz Date: 21/02/15 Time: 21:52 */

public class MyThread extends Thread {

    int x = 0;

    @Override
    public synchronized void run() {
        System.out.println("Thread running..");
        while(x == 0) {
        }
        while(x != 1) {
            System.out.println("x is" + x);
            // do something else time consuming
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void foo(int y) {
        x = y;
    }

}

When I run TestClass like this: 当我像这样运行TestClass时:

/* User: koray@tugay.biz Date: 21/02/15 Time: 21:55 */

public class TestClass {

    public static void main(String[] args) throws InterruptedException {

        MyThread myThread = new MyThread();
        myThread.start();
        //Thread.sleep(1000);
        myThread.foo(3);

    }
}

I see in the console: 我在控制台中看到:

Thread running..
x is3
x is3
x is3
x is3

which is ok.. 没关系..

But when I uncomment the //Thread.sleep(1000); 但是当我取消注释 //Thread.sleep(1000); I expect the same behaviour, only after 1 second.. But all I see in the Console is. 我希望只有1秒后才会有相同的行为。.但是我在控制台中看到的只是。

Thread running..

No matter how long I wait.. 不管我等多久

Why? 为什么?

您需要让Java知道x的值可能由另一个线程使用volatile关键字更新:

volatile int x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM