1 package com.review; 2 /** 3 * @program: com.review 4 * @description: 5 * @author: Mr.Lin 6 * @create: 2019年8月14日 7 **/ 8 public class Resident extends Thread{ 9 private MiddleMan mid = null; 10 public Resident() { 11 } 12 public Resident(MiddleMan movie) { 13 this.mid = movie; 14 } 15 @Override 16 public void run() { 17 for (int i = 0; i <1000 ; i++) { 18 try { 19 Thread.sleep(100); 20 }catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 this.mid.get(); 24 } 25 } 26 27 }
1 package com.review; 2 /** 3 * @program: com.review 4 * @description: 5 * @author: Mr.Lin 6 * @create: 2019年8月14日 7 **/ 8 public class Staff implements Runnable{ 9 //生产数据 10 private MiddleMan mid = null; 11 private boolean flag = false; 12 13 public Staff(MiddleMan movie) { 14 this.mid = movie; 15 } 16 public Staff() { 17 } 18 19 @Override 20 public void run() { 21 // TODO Auto-generated method stub 22 for (int i = 0; i <1000; i++) { 23 if (flag){ 24 this.mid.set("jack说:","我是查水表"); 25 flag = false; 26 }else { 27 this.mid.set("rose说:","你是谁啊?"); 28 flag = true; 29 } 30 } 31 32 } 33 34 }
1 package com.review; 2 /** 3 * @program: com.review 4 * @description: 5 * @author: Mr.Lin 6 * @create: 2019年8月14日 7 **/ 8 public class MiddleMan { 9 private String name; 10 private String info; 11 private boolean flag = true; 12 13 public String getName() { 14 return name; 15 } 16 17 public String getInfo() { 18 return info; 19 } 20 21 public MiddleMan(String name, String info) { 22 this.name = name; 23 this.info = info; 24 } 25 26 public MiddleMan() { 27 } 28 29 public synchronized void set(String name,String info){ 30 if (!flag){ 31 try { 32 super.wait(); 33 }catch (InterruptedException e) { 34 e.printStackTrace(); 35 } 36 } 37 this.name = name; 38 try { 39 Thread.sleep(100); 40 }catch (InterruptedException e) { 41 e.printStackTrace(); 42 } 43 this.info = info; 44 flag = false; 45 super.notify(); 46 } 47 public synchronized void get(){ 48 if (flag){ 49 try { 50 super.wait(); 51 }catch (InterruptedException e) { 52 e.printStackTrace(); 53 } 54 } 55 System.out.println(this.getName()+"-"+this.getInfo()); 56 flag = true; 57 super.notify(); 58 } 59 60 }
1 package com.review; 2 /** 3 * @program: com.review 4 * @description: 5 * @author: Mr.Lin 6 * @create: 2019年8月14日 7 **/ 8 public class Test { 9 public static void main(String[] args) { 10 MiddleMan mid = new MiddleMan(); 11 Thread Staff = new Thread(new Staff(mid)); 12 Thread Resident = new Thread(new Resident(mid)); 13 Staff.start(); 14 Resident.start(); 15 } 16 17 }