java用this- gt_Java并发:同步(this)=>和this.wait()和this.notify()

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

}

报价结束:

我的问题是:为什么这段代码有效?

=&GT当我同步“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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值