Java并发:同步(this)=>和this.wait()和this.notify() [英] Java Concurrency : Synchronized(this) => and this.wait() and this.notify()

查看:390
本文介绍了Java并发:同步(this)=>和this.wait()和this.notify()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您帮助理解并发示例:
http://forums.sun.com/thread.jspa?threadID=735386

I would appreciate your help in understand a "Concurrency Example" from: 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
}

报价结束:

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

My Question is: Why is this code valid?

=>当我同步 public synchronized =>等方法时,我会同步实例对象==>
但是在上面的示例中:

=> When I synchronize a method like "public synchronized" => then I synchronize on the "Instance of the Object ==> this". However in the example above:


  1. 调用dequeue我将获得

现在我在出队方法。由于列表为零,调用线程将为等待

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

Backround:我有完全相同的问题:我有某种连接池(连接列表),如果检查了所有连接,则需要阻止。如果大小超过限制或为零,将List同步到阻止的正确方法是什么?

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?

非常感谢

Jens

推荐答案

参见: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html #wait()


当前线程必须拥有此对象的监视器。线程释放
对此监视器的所有权并等待,直到另一个线程通知
线程等待此对象的监视器通过
调用 notify 方法或 notifyAll 方法。线程然后
等待,直到它可以重新获得监视器的所有权并恢复
执行。

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()时,线程持有的监视器被释放,允许入队(以及在上同步的其他操作 object)在另一个线程上调用。当通知线程时,它会在继续之前尝试再次获取监视器。

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.

这篇关于Java并发:同步(this)=>和this.wait()和this.notify()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆