【发布时间】:2017-05-08 09:26:49
【问题描述】:
我有一个线程,当它运行时,它会创建一个 Message 对象,该对象被放入监视器的链表中。同时,另外两个线程等待这个列表获取一个Message对象在里面,一会儿(linkedlist.isEmpty()) canGetMessage.await();循环,但即使我正在发送 canGetMessage.signalAll();命令将对象放入列表时,其他两个线程永远不会唤醒。
public void deliverMessage(Message m){
lock.lock();
try{
linkedlist.add(m);
canGetMessage.signalAll();
}finally{
lock.unlock();
}
}
public Message getMessage(){
lock.lock();
try{
while(linkedlist.isEmpty()){
canGetMessage.await();
}
return linkedlist.remove(); //returns the item that has been in the list the longest
}
catch (InterruptedException e) { } //not required to handle these
finally{
lock.unlock();
}
我有 println 来查看它何时退出 while 循环,但这从未发生过,我不知道为什么......
编辑:只是为了说明,我使用的锁是 ReentrantLock
【问题讨论】:
-
为什么不使用 BlockingQueue 和生产者-消费者模式?
-
发布一个完整的最小示例来重现问题。
-
lock、linkedlist和canGetMessage有哪些类型,它们是如何创建的?而且,是的,MCVE 会非常有用。
标签: java multithreading