ConcurrentHashMap wait for key possible?

后端 未结 3 2013
心在旅途
心在旅途 2021-01-13 17:24

i have multithread communication. 1 Thread is dispatching datas to other threads.

Main thread is pushing data:

Main Thread: ConcurrentHashMap map = Glob

3条回答
  •  鱼传尺愫
    2021-01-13 17:59

    You can use BlockingQueue if you allowed to change your implementation, or use a wait/notify technique to wait and run when occupy.

    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.
        }
    }
    

    and for producer:

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

提交回复
热议问题