这个程序的答案需要在5秒后变成“Changing done”,但是我得到的却是“Changing done”和“DONE”。我的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;
}
}
Runnable
不会完成? - CodeBlinddone
的同步不正确,调用getDone()
可能无法看到当前值。 - user140547