我有下一个代码:
boolean signal;
@Test
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (!signal){
// empty loop body
}
}
});
thread.start();
Thread.sleep(1000);
signal = true;
thread.join();
}由于在线程中创建了signal变量的本地副本,它会运行无限循环。我知道我可以通过将我的signal变量设置为volatile来修复它。但是如果在我的循环中添加synchronized块(即使是空的),循环也可以成功退出:
boolean signal;
@Test
public void test() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (!signal){
synchronized (this) {
}
}
}
});
thread.start();
Thread.sleep(1000);
signal = true;
thread.join();
}synchronized如何在线程内更新我的signal值?
发布于 2016-07-08 23:13:52
Synchronized并不更新信号值本身,它基本上只是放置了几个标志,以避免两个线程同时使用相同的对象;例如: MonitorEnter和MonitorExit。
第一个锁住对象,第二个释放。
请看下面的文章:how-the-java-virtual-machine-performs-thread-synchronization。
请注意,这篇文章非常陈旧;但据我所知,背后的逻辑仍然存在。
https://stackoverflow.com/questions/38269709
复制相似问题