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

该博客讨论了Java中队列同步容器的`enqueue`和`dequeue`方法的并发控制。当`dequeue`方法检测到队列为空时,它会释放锁并等待被唤醒。而当`enqueue`方法添加元素后,会通知等待的线程。因此,并没有死锁,因为`wait()`调用会释放锁,允许其他线程执行`enqueue`。正确的同步方式确保了在连接池满或空时,线程能够正确地阻塞和唤醒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I would appreciate your help in understand a "Concurrency Example" from:

http://forums.sun.com/thread.jspa?threadID=735386

Qute Start:

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

}

Quote End:

My Question is: Why is this code valid?

=> When I synchronize a method like "public synchronized" => then I synchronize on the "Instance of the Object ==> this".

However in the example above:

Calling "dequeue" I will get the "lock/monitor" on this

Now I am in the dequeue method. As the list is zero, the calling thread will be "waited"

From my understanding I have now a deadlock situation, as I will have no chance of ever enquing an object (from an nother thread), as the "dequeue" method is not yet finised and the dequeue "method" holds the lock on this: So I will never ever get the possibility to call "enequeue" as I will not get the "this" lock.

Backround: I have exactly the same problem: I have some kind of connection pool (List of Connections) and need to block if all connections are checked. What is the correct way to synchronize the List to block, if size exceeds a limit or is zero?

Thank you very much

Jens

解决方案

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.

So no, there is no deadlock. When wait() is called, the monitor held by the thread is released, allowing enqueue (and other operations that are synchronized on this object) to be called on another thread. When the thread is notified, it will try to obtain the monitor again before continuing.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值