sat*_*son 3 java multithreading synchronized java-8
这个程序的答案必须在5秒后完成"改变完成",但我得到"改变完成"和"完成".我没有getDone方法同步.我有什么想法为线程完成处理.
public class Main {
private static boolean done = false;
private static int count;
public static void main(String[] args)throws InterruptedException {
new Thread(() -> {
while (!getDone()) {
count = count + 1;
}
System.out.println("DONE!!!!");
}).start();
Thread.sleep(5000);
System.out.println("Changing done");
synchronized (Main.class) {
done = true;
}
}
public static boolean getDone() {
return done;
}
}
Run Code Online (Sandbox Code Playgroud)
如果未done正确同步访问,则表示您的代码可能会失败,即线程可能看不到更新的值.
除非正确同步,否则并不意味着保证值不可见.因此,在许多情况下,写入done仍然是可见的(在许多情况下,破坏的代码仍然有效,这使得并发编程更加困难).它并不能保证在每种情况下都能正常工作.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |