线程间的通信

 1 package com.cn;
 2 
 3 class Test{
 4     public static void main(String [] args){
 5         Q q = new Q();
 6         new Thread(new Producer(q)).start();
 7         new Thread(new Consumer(q)).start();
 8     }
 9 }
10 
11 class Q{
12     String name = "unknow";
13     String sex = "unknow";
14     boolean bFull = false;
15     public synchronized void put(String name,String sex){
16         if(bFull)
17             try {
18                 wait();
19             } catch (InterruptedException e1) {
20                 e1.printStackTrace();
21             }
22         this.name = name;
23         try {
24             Thread.sleep(10);
25         } catch (InterruptedException e) {
26             e.printStackTrace();
27         }
28         this.sex = sex;
29         bFull = true;
30         notify();
31     }
32     public synchronized void get(){
33         if(!bFull)
34             try {
35                 wait();
36             } catch (InterruptedException e) {
37                 e.printStackTrace();
38             }
39         System.out.print(name);
40         System.out.println(":"+sex);
41         bFull = false;
42         notify();
43     }
44 }
45 
46 class Producer implements Runnable{
47     Q q;
48     public Producer(Q q){
49         this.q = q;
50     }
51     public void run(){
52         int i = 0;
53         while(true){
54             if(i==0){
55                 q.put("zhangsan", "male");
56             }else{
57                 q.put("lisi", "famale");
58             }
59             i = (i+1)%2;
60         }
61     }
62 }
63 
64 class Consumer implements Runnable{
65     Q q;
66     public Consumer(Q q){
67         this.q = q;
68     }
69     public void run(){
70         while(true){
71             q.get();
72         }
73     }
74 }

保证了生产者生产了一个,消费者才可以去取一个,缓冲区存在已经生产的一个时生产者不会再生产,而是通知并等待消费者去取,在缓冲区没有事,消费者也不会去取,而是通知并等待生产者去生产。

原文地址:https://www.cnblogs.com/lzy1991/p/5111564.html