java - 同步 HashMap 访问

标签 java multithreading hashmap synchronization

在我的电脑上,使用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/

相关文章:

javascript - AngularJS 从 Java Map 填充 ng-options 选项。 (排序问题)

java - 在 HashMap 中存储一个数组

java - 字符串数组转入HashMap集合对象

java - 如何在Android中解析JSON数组(不是Json对象)

java - 合并排序程序没有给出正确的结果?

c++ - 我怎么知道线程是否是可连接线程?

linux - 在调用 pthread_join(th,NULL) 之后调用 pthread_detach(th) 有什么意义吗?

java - 如何将带有对象和数组索引的字符串转换为 json

java - maven-jaxb2-plugin 中的 AutoNameResolution

wpf绑定(bind): The calling thread cannot access this object because a different thread owns it