线程wait和notify方法的demo详解
wait和notify都是针对某个线程而言的:
package com.roocon.thread.t1; public class NewThread implements Runnable { @Override public void run() { while(true){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("自定义线程运行了"); } } public static void main(String[] args) { NewThread n = new NewThread(); Thread thread = new Thread(n);//创建线程并且指定线程任务 thread.start();//启动线程 while(true){ System.out.println("主线程运行了"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } n.notifyAll(); } } }
运行,发现报错如下:

原因:调用wait和notify以及notifyAll,它其实是要跟一个同步监视器的。而且同步监视器所指定的对象必须是当前类的实例。修改代码如下:
package com.roocon.thread.t1; public class NewThread implements Runnable { @Override public synchronized void run() { while(true){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("自定义线程运行了"); } } public static void main(String[] args) { NewThread n = new NewThread(); Thread thread = new Thread(n);//创建线程并且指定线程任务 thread.start();//启动线程 while(true){ synchronized (n){ System.out.println("主线程运行了"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } n.notifyAll(); } } } }
运行结果如下:

总结:
首先,自定义线程执行代码还是主线程执行代码,这个是看哪个线程先获取CPU。
当自定义线程执行代码时,发现有wait方法,则进入等待状态,于是主线程开始执行,执行完后遇到notifyAll,则会去通知阻塞状态的n,此时n会被幻想,于是,线程n开始执行它的代码,输出,自定义线程执行了。自定义线程执行完后又开始等待了。...一直这样循环下去。
作者:凌晨六点半
出处:http://www.cnblogs.com/sunnyDream/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能 打赏我一杯咖啡【物质支持】,也可以点击右下角的【好文要顶】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力!

浙公网安备 33010602011771号