ConcurrentHashMap等待密钥可能吗?

我有multithreading的沟通。 1线程正在将数据分派给其他线程。

主线程正在推送数据:

主线程:ConcurrentHashMap map = Global.getInstance()。getMap(); //将数据推送到其他一些线程map.put(1,“Test”);

线程1:字符串数据= map.get(1); //直接返回null,但我想等到推送数据

如果主线程没有推送任何数据,则线程1返回null。 但我想等到有数据,我该怎么办?

TransferQueue不是我当前实现的好方法。 我必须使用ConcurrentHashMap。

有人知道任何解决方案吗?

你可以创建一个像这样的BlockingMap; 根据使用情况,您还应设置一种机制来删除与其关联的未使用的密钥和队列,以避免内存泄漏。

public class BlockingMap { private final Map> map = new ConcurrentHashMap<>(); private synchronized BlockingQueue ensureQueueExists(K key) { //concurrentMap.putIfAbsent would require creating a new //blocking queue each time put or get is called if (map.containsKey(key)) { return map.get(key); } else { BlockingQueue queue = new ArrayBlockingQueue<>(1); map.put(key, queue); return queue; } } public boolean put(K key, V value, long timeout, TimeUnit timeUnit) { BlockingQueue queue = ensureQueueExists(key); try { return queue.offer(value, timeout, timeUnit); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public V get(K key, long timeout, TimeUnit timeUnit) { BlockingQueue queue = ensureQueueExists(key); try { return queue.poll(timeout, timeUnit); } catch (InterruptedException e) { throw new IllegalStateException(e); } } } 

从Java 8开始,可以编写ensureQueueExists

 private synchronized BlockingQueue ensureQueueExists(K key) { map.computeIfAbsent(key, k -> new ArrayBlockingQueue<>(1)); } 

如果您允许更改实现,则可以使用BlockingQueue ,或者在占用时使用等待/通知技术等待并运行。

 String value = null; while(true) { if((value = map.get(1)) != null) { // VARY IMPORTANT to use get and != // work with value } else { map.wait(); // should be in a synchronized block. } } 

并为生产者:

 String value = "Test"; map.put(1,value); map.notifyAll(); // or notify(). 

首先,在从Map获取值之前,在线程1上调用wait() 。 然后,您可以扩展ConcurrentHashMap并覆盖put()方法,以便在新数据可用时notify()线程1。