这是我的代码:
/* 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;
}
}
当我像这样运行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);
}
}
我在控制台中看到:
Thread running..
x is3
x is3
x is3
x is3
没关系..
但当我取消注释 //Thread.sleep(1000);我期待相同的行为,仅在1秒后......但我在控制台中看到的只是。
Thread running..
无论我等多久......
为什么?
答案 0 :(得分:1)
您需要让Java知道x
的值可能会被另一个线程使用volatile
关键字更新:
volatile int x;