线程的通讯:一个线程完成了自己的任务时,要通知另一个线程去完成另一个任务
1.1、方法
wait():等待。如果线程执行到了wait()方法,那么该线程会进入等待状态,等待状态下的线程必须要被其他线程调用notify()方法才能唤醒.
notify():唤醒。唤醒线程池等待的其中一条线程
notifyAll():唤醒线程池中所等待的线程
1.2、wait与notyify的方法注意的事项
1. wait方法与notify方法是属于Object对象的
2.wait与notify方法必须要在同步代码块或者同步函数中才能使用
3.wait方法与notify的方法必须由锁对象调用
1.3、实例
1 package com.zn.thread; 2 3 /** 4 * @author DSHORE / 2018-5-11 5 * 6 */ 7 /* 8 * 线程的通讯:一个线程完成了自己的任务时,要通知另一个线程去完成另一个任务 9 * 10 * 生产者与消费者 11 * 12 * */ 13 //产品 14 class Product{ 15 String name;//产品名字 16 double price;//价格 17 boolean flag=false;//生产者是否生产完成的标志,默认是没有生产完成 18 } 19 //生产者 20 class Producer extends Thread{ 21 Product p; 22 public Producer(Product p) { 23 this.p=p; 24 } 25 @Override 26 public void run() { 27 int i=0; 28 while(true){ 29 synchronized (p) { 30 if(p.flag==false){ 31 if(i%2==0){ 32 p.name="苹果"; 33 p.price=5.0; 34 }else{ 35 p.name="香蕉"; 36 p.price=3.5; 37 } 38 System.out.println("生存者生产出了:"+p.name+"; 价格是:"+p.price); 39 p.flag=true;//flag为true时,通知消费者去消费 40 i++; 41 p.notify();//唤醒 消费者去消费 42 }else{ 43 try { 44 p.wait();//生产者等待 45 } catch (InterruptedException e) { 46 e.printStackTrace();//打印异常信息 47 } 48 } 49 } 50 } 51 } 52 } 53 //消费者 54 class Customer extends Thread{ 55 Product p; 56 public Customer(Product p) { 57 this.p=p; 58 } 59 @Override 60 public void run() { 61 while(true){ 62 synchronized (p) { 63 if(p.flag==true){ 64 System.out.println("消费者消费了:"+p.name+"; 价格:"+p.price); 65 p.flag=false;//flag为false时,通知生产者去生产 66 p.notify();//唤醒 生产者去生产 67 }else{ 68 try { 69 p.wait();//消费者也等待了 70 } catch (InterruptedException e) { 71 e.printStackTrace();//打印异常信息 72 } 73 } 74 75 } 76 } 77 } 78 } 79 public class Demo5 { 80 public static void main(String[] args) { 81 Product p=new Product(); 82 //创建线程对象 83 Producer producer=new Producer(p); 84 Customer customer=new Customer(p); 85 //开启线程 86 producer.start(); 87 customer.start(); 88 } 89 }
运行结果图
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:http://www.cnblogs.com/dshore123/p/9010165.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |