【发布时间】:2010-05-19 04:18:59
【问题描述】:
如果您能帮助理解以下“并发示例”,我将不胜感激: http://forums.sun.com/thread.jspa?threadID=735386
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”之类的方法时 => 然后我在“对象实例 ==> this”上进行同步。
但是在上面的例子中:
-
调用“dequeue”我将在
this上获得“锁定/监控” -
现在我在 dequeue 方法中。由于列表为零,调用线程将是“
waited” -
据我了解,我现在遇到了死锁情况,因为“出队”方法尚未完成,出队“方法”将锁定锁定
this:所以我永远不可能调用“enqueue”,因为我不会得到“this”锁。
背景:我有完全相同的问题:我有某种连接池(连接列表),如果检查了所有连接,则需要阻止。如果大小超过限制或为零,同步列表以阻止的正确方法是什么?
【问题讨论】:
标签: java concurrency