感谢您帮助理解"并发示例":http: //forums.sun.com/thread.jspa?threadID = 735386
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
}
Run Code Online (Sandbox Code Playgroud)
报价结束:
我的问题是:为什么这段代码有效?
=>当我同步像" public synchronized"=> 这样的方法时,我同步"对象的实例==> this".但是在上面的例子中:
呼叫"出列"我将打开"锁定/监视器" this
现在我在出队方法.由于列表为零,调用线程将为" waited"
this:所以我永远不会有可能称之为"enequeue",因为我不会得到this"锁定".Backround:我有完全相同的问题:我有一些连接池(连接列表),如果检查所有连接,需要阻止.如果大小超过限制或为零,将List同步到阻止的正确方法是什么?
非常感谢你
延
请参阅:http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
当前线程必须拥有此对象的监视器.线程释放此监视器的所有权并等待,直到另一个线程通过调用
notify方法或notifyAll方法通知等待此对象的监视器上的线程唤醒.然后线程等待,直到它可以重新获得监视器的所有权并继续执行.
所以不,没有僵局.当wait()被调用时,由线程持有监视器被释放,允许入队(那是在同步等操作this的对象)被另一个线程调用.当通知线程时,它将尝试再次获取监视器,然后继续.
| 归档时间: |
|
| 查看次数: |
7212 次 |
| 最近记录: |