Qute开始:
public synchronized void enqueue(T obj) {
// do addition to internal list and then...
this.notify();
}
public synchronized T dequeue() {
while (this.size()==0) {
this.wait();
}
return // something from the queue
}
报价结束:
我的问题是:为什么这段代码有效?
=>当我同步“public synchronized”=>这样的方法时然后我同步“对象的实例==>这个”.
但是在上面的例子中:
>调用“出列”我会得到“锁定/监视”
>现在我处于出列方法中.由于列表为零,调用线程将“等待”
>根据我的理解,我现在有一个死锁的情况,因为我没有机会从一个其他线程中获取一个对象,因为“dequeue”方法尚未完成,并且dequeue“method”持有对此的锁定:所以我永远不会有可能称之为“enequeue”,因为我不会得到“这个”锁定.
Backround:我有完全相同的问题:我有一些连接池(连接列表),如果检查所有连接,需要阻止.如果大小超过限制或为零,将List同步到阻止的正确方法是什么?
非常感谢你
延
解决方法:
The current thread must own this object’s monitor. The thread releases
ownership of this monitor and waits until another thread notifies
threads waiting on this object’s monitor to wake up either through a
call to the notify method or the notifyAll method. The thread then
waits until it can re-obtain ownership of the monitor and resumes
execution.
所以不,没有僵局.当调用wait()时,线程保持的监视器被释放,允许在另一个线程上调用enqueue(以及在此对象上同步的其他操作).当通知线程时,它将尝试再次获取监视器,然后继续.
标签:java,concurrency
来源: https://codeday.me/bug/20190726/1546181.html