在我的电脑上,使用java 8,即使 map 访问同步,以下程序也不会停止。这些同步块(synchronized block)还不够吗?
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
// Broken! - How long would you expect this program to run?
public class StopThread {
private static HashMap<String, String> stopRequested = new HashMap<String, String>();
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
synchronized (stopRequested) {
while (stopRequested.get("stop") == null)
i++;
}
System.out.println(i);
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
synchronized (stopRequested) {
stopRequested.put("stop", "true");
}
}
}
最佳答案
这将永远运行。同步块(synchronized block)中的 while 循环实际上是无限的,因为它首先进入 - 因此禁止进入第二个同步块(synchronized block)。
关于java - 同步 HashMap 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44242352/