多线程-线程间通信-多生产者多消费者问题

 1 package multithread4;
 2 
 3 /*
 4  * 生产者,消费者。
 5  * 
 6  * 死锁 四个线程都等待没有被唤醒也是一种情况
 7  */
 8 
 9 class Resource2{
10     private String name;
11     private int count = 1;
12     private boolean flag = false;
13     public synchronized void set(String name) {
14         
15 /*if*/ while (flag) {
16             try {
17                 this.wait();
18             } catch (InterruptedException e) {
19                 
20             }
21         }
22         this.name = name + count;
23         count++;
24         System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
25         flag = true;
26         notify();
27     }
28     public synchronized void out() {
29 /*if*/ while (!flag) {
30             try {
31                 this.wait();
32             } catch (InterruptedException e) {
33                 
34             }
35         }
36         System.out.println(Thread.currentThread().getName()+"..消费者......"+this.name);
37         flag = false;
38         notify();
39     }
40 }
41 
42 class Producer implements Runnable{
43     private Resource2 r;
44     public Producer(Resource2 r) {
45         this.r = r;
46     }
47     public void run() {
48         while(true) {
49             r.set("烤鸭");
50         }
51     }
52 }
53 class Consumer implements Runnable{
54     private Resource2 r;
55     public Consumer(Resource2 r) {
56         this.r = r;
57     }
58     public void run() {
59         while(true) {
60             r.out();
61         }
62     }
63 }
64 public class ProducerConsumerDemo {
65 
66     public static void main(String[] args) {
67         
68         Resource2 r = new Resource2();
69         Producer pro = new Producer(r);
70         Consumer con = new Consumer(r);
71         
72         Thread t0 = new Thread(pro);
73         Thread t1 = new Thread(pro);
74         Thread t2 = new Thread(con);
75         Thread t3 = new Thread(con);
76         
77         t0.start();
78         t1.start();
79         t2.start();
80         t3.start();
81     }
82 
83 }
ProducerConsumerDemo

 

posted @ 2021-11-11 11:37  doremi429  阅读(12)  评论(0编辑  收藏  举报