2019独角兽企业重金招聘Python工程师标准>>>

Java wait && notify

wait、notify和notifyAll方法是Object类的final native方法,所以这些方法不能被子类重写。

方法 notifyAll()

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the{wait} methods.

该方法只能在同步方法或同步块内部调用。如果当前线程不是锁的持有者,该方法抛出一个IllegalMonitorStateException异常。

方法 notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the {wait} methods.

该方法只能在同步方法或同步块内部调用。如果当前线程不是锁的持有者,该方法抛出一个IllegalMonitorStateException异常。

方法 wait()

Causes the current thread to wait until another thread invokes the {java.lang.Object#notify()} method or the {java.lang.Object#notifyAll()} method for this object.The current thread must own this object's monitor. 

调用该方法的线程进入WAITING 状态,只有等待另外线程的通知或被中断才会返回,需要注意的是调用wait方法后,才会释放对象的锁。

该方法只能在同步方法中调用。如果当前线程不是锁的持有者,该方法抛出一个IllegalMonitorStateException异常。下面是一个wait的示例

synchronized (object) {while (<condition does not hold>)object.wait();// ...
}

方法 wait(long millis)&&wait(long millis,int nanos)

Causes the current thread to wait until another thread invokes the { java.lang.Object#notify()} method or the {java.lang.Object#notifyAll()} method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed(消逝,过去).

超时等待一段时间后,这里的参数时间是毫秒,也就是等待长达n毫秒,如果没有通知就超时返回。

这些方法只能在同步方法中调用。如果当前线程不是锁的持有者,该方法抛出一个IllegalMonitorStateException异常。

timeout -- 最大的等待时间(以毫秒为单位)。

nanos   -- 额外的时间,在纳秒范围为0-999999。

‍Object.wait()和Object.notify()和Object.notifyAll()必须写在synchronized方法内部或者synchronized块内部,这是因为:这几个方法要求当前正在运行object.wait()方法的线程拥有object的对象锁(内置锁)。即使你确实知道当前上下文线程确实拥有了对象锁,也不能将object.wait()这样的语句写在当前上下文中。‍

下面这段代码的写法是错误的。

package sync;class A {public synchronized void printThreadInfo() throws InterruptedException {Thread t = Thread.currentThread();System.out.println("ThreadID:" + t.getId() + ", ThreadName:" + t.getName());}
}public class ObjectWaitTest {public static void main(String args[]) {A a = new A();//因为printThreadInfo()方法抛出InterruptedException异常,所以这里必须使用try-catch块try {a.printThreadInfo();a.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

应该要这么写:

package sync;class A {public synchronized void printThreadInfo() throws InterruptedException {Thread t = Thread.currentThread();System.out.println("ThreadID:" + t.getId() + ", ThreadName:" + t.getName());// this.wait();//一直等待this.wait(1000);//等待1000ms// super.wait(1000);}
}public class ObjectWaitTest {public static void main(String args[]) {A a = new A();//因为printThreadInfo()方法抛出InterruptedException异常,所以这里必须使用try-catch块try {a.printThreadInfo();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}Thread t = Thread.currentThread();System.out.println("ThreadID:" + t.getId() + ", ThreadName:" + t.getName());}
}

完整示例,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;public class WaitNotifyDemo {static boolean flag = true;static Object lock = new Object();public static void main(String[] args) throws InterruptedException {Thread waitThread = new Thread(new Wait(), "waitThread");waitThread.start();TimeUnit.SECONDS.sleep(1);Thread notifyThread = new Thread(new Notify(), "notifyThread");notifyThread.start();}static class Wait implements Runnable {@Overridepublic void run() {// 加锁 拥有lock 的 monitorsynchronized (lock) {while (flag) {try {System.out.println(Thread.currentThread() + " flag is true. wait @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));// 释放了对象的监视器锁lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread() + " flag is false. running @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));}}}static class Notify implements Runnable {@Overridepublic void run() {synchronized (lock) {System.out.println(Thread.currentThread() + " hold lock. notify @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));lock.notifyAll();flag = false;try {Thread.sleep(1000 * 5);} catch (InterruptedException e) {e.printStackTrace();}}}}
}

以上就是关于wait和notify方法的用法。

参考:http://www.cnblogs.com/xwdreamer/archive/2012/05/12/2496843.html

后记:Thread.sleep()与Object.wait()二者都可以暂停当前线程,释放CPU控制权,主要的区别在于Object.wait()在释放CPU同时,释放了对象锁的控制。

==============END==============

转载于:https://my.oschina.net/xinxingegeya/blog/345816

Java wait notify相关推荐

  1. Java中notify和notifyAll的区别 - 何时以及如何使用

    Java  notify   vs notifyAll notify和notifyAll方法之间有什么区别是棘手的Java问题之一! Condition 是个什么玩意? 提几个问题,从问题中去了解去学 ...

  2. java thread.notify,Java Thread notify()方法

    Java Thread notify()方法 java.lang.Thread.notify() 方法用于唤醒单个线程.此方法仅针对正在等待特定对象的一个线程给出通知.如果我们使用notify() 方 ...

  3. Java之notify和notifyAll区别

    在Java中notify()和notifyAll()方法都是Object对象用于通知处在等待该对象的线程的方法. 两者的最大区别在于: notifyAll方法 使所有原来在该对象上等待被notify的 ...

  4. lua java 性能比较_Lua coroutine vs Java wait/notify

    在上文Lua coroutine 不一样的多线程编程思路中想到coroutine的运行机制跟Java中的wait/notify很相似,所以写了一个简单程序比较一下. 源代码 Lua code co = ...

  5. JAVA wait(), notify(),sleep具体解释

    在CSDN开了博客后,一直也没在上面公布过文章,直到前一段时间与一位前辈的对话,才发现技术博客的重要,立志要把CSDN的博客建好.但一直没有找到好的开篇的主题,今天再看JAVA线程相互排斥.同步的时候 ...

  6. Lua coroutine vs Java wait/notify

    在上文Lua coroutine 不一样的多线程编程思路 中想到coroutine的运行机制跟Java中的wait/notify很相似,所以写了一个简单程序比较一下. 源代码 Lua code co ...

  7. java中notify是什么意思_java中wait,notify,notifyAll是什么?

    wait(),notify(),notifyAll()不属于Thread类,而是属于Object基础类,也就是说每个对像都有wait(),notify(),notifyAll() 的功能.因为都个对像 ...

  8. Java 中 notify 和 notifyAll 有什么区别?

    notify() 方法不能唤醒某个具体的线程,所以只有一个线程在等待的时候它才有 用武之地.而 notifyAll()唤醒所有线程并允许他们争夺锁确保了至少有一个线程 能继续运行.

  9. Java多线程——notify()与notifyAll()的区别

    notify(): 唤醒在此对象监视器上等待的单个线程.如果所有线程都在此对象上等待,则会选择唤醒其中一个线程.选择是任意性的,并在对实现做出决定时发生.线程通过调用其中一个 wait 方法,在对象的 ...

最新文章

  1. android返回键方法,Android按返回键(后退键)Back键事件捕获的两种方法
  2. QT的QSignalTransition类的使用
  3. 查python答案的软件-中国大学MOOC的APP慕课用Python玩转数据答案查题公众号
  4. IBatisNet + Castle 开发相关文章
  5. IDEA导入Eclipse项目的方法步骤(图文教程)
  6. atiny_log | LiteOS 物联网操作系统中的日志打印组件使用分享
  7. android怎么用经纬度定位,android 根据经纬度定位所在城市
  8. java软件工程师工作业绩_java软件工程师的工作描述怎么写
  9. 入门学习必收藏!精选Photoshop、D…
  10. iPad/iPhone与电脑共享文件
  11. 电脑上打开chm文件时系统提示:不能打开文件:mk:@MSITStore:(文件路径)
  12. 转帖-[教程] Win7精简教程(简易中度)2016年8月-0day
  13. 数学建模之稳定性模型详解
  14. 【Codeforces Round#618 (Div. 2)】C. Anu Has a Function 题解
  15. 天猫首创“服务360”平台 赋能商家提升用户体验
  16. 什么叫克隆人_什么叫克隆技术?为什么不允许克隆人
  17. 怎么给自己的U盘加密
  18. 2022-2028全球牛油果市场专题研究及投资评估报告
  19. 关于pdf文件直接在chrome浏览器中直接打开而不是下载的问题
  20. win10跨网段共享计算机,win10系统电脑之间实现跨网段共享打印机的恢复教程

热门文章

  1. OSChina 周三乱弹 —— 爸爸说,这个是从他硬盘里掉出来的
  2. Android系统的开机画面显示过程分析(8)
  3. 利用反射做类参数的校验
  4. ***关于WP的邮件无法发送问题的总结(原创)
  5. 记录最近的一些遇到的前端面试题
  6. 正则验证金额大于等于0,并且只到小数点后2位
  7. 算法学习笔记(三)-----各种基础排序问题
  8. Linux查看硬件信息很Easy
  9. Cisco 胖AP和瘦AP的区别
  10. mysql数据库三大引擎优缺点