码迷,mamicode.com
首页 > 编程语言 > 详细

java wait()和notify()、notifyAll()

时间:2016-05-11 13:13:19      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

3、wait()和notify()、notifyAll()

wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
notify(): Wakes up a single thread that is waiting on this object‘s monitor.
notifyAll(): Wakes up all threads that are waiting on this object‘s monitor.

这三个方法用于协调多个线程对共享数据的存取,所以必须在synchronized语句块内使用

synchronized关键字用于保护共享数据,阻止其 他线程对共享数据的存取,但是这样程序的流程就很不灵活了,如何才能在当前线程还没退出synchronized数据块时让其他线程也有机会访问共享数据 呢?此时就用这三个方法来灵活控制。wait() 方法使当前线程暂停执行并释放对象锁标示,让其他线程可以进入synchronized数据块,当前线程被放入对象等待池中。当调用notify()方法 后,将从对象的等待池中移走一个任意的线程并放到锁标志等待池中,只有锁标志等待池中线程能够获取锁标志;如果锁标志等待池中没有线程,则 notify()不起作用。

notifyAll()则从对象等待池中移走所有等待那个对象的线程并放到锁标志等待池中。注意 这三个方法都是java.lang.Object的方法。

 

java wait()和notify()、notifyAll()

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/5481420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!