1 package multithread4; 2 3 /* 4 * 生产者,消费者。 5 * 6 * 多生产者,多消费者的问题。 7 * 8 * if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。 9 * while判断标记,解决了线程获取执行权后,是否要运行! 10 * 11 * notify:只能唤醒一个线程,如果本方唤醒了本方,没有意义。而且while判断标记+notify会产生死锁 12 * notifyAll解决了,本方线程一定会唤醒对方线程 13 * 14 * 死锁 四个线程都等待没有被唤醒也是一种情况,悬挂 15 */ 16 17 class Resource2{ 18 private String name; 19 private int count = 1; 20 private boolean flag = false; 21 public synchronized void set(String name) { 22 23 /*if*/ while (flag) { 24 try { 25 this.wait(); 26 } catch (InterruptedException e) { 27 28 } 29 } 30 this.name = name + count; 31 count++; 32 System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name); 33 flag = true; 34 // notify(); 35 notifyAll(); 36 } 37 public synchronized void out() { 38 /*if*/ while (!flag) { 39 try { 40 this.wait(); 41 } catch (InterruptedException e) { 42 43 } 44 } 45 System.out.println(Thread.currentThread().getName()+"..消费者......"+this.name); 46 flag = false; 47 // notify(); 48 notifyAll();//为了解决死锁 将其余三个都唤醒 49 } 50 } 51 52 class Producer implements Runnable{ 53 private Resource2 r; 54 public Producer(Resource2 r) { 55 this.r = r; 56 } 57 public void run() { 58 while(true) { 59 r.set("烤鸭"); 60 } 61 } 62 } 63 class Consumer implements Runnable{ 64 private Resource2 r; 65 public Consumer(Resource2 r) { 66 this.r = r; 67 } 68 public void run() { 69 while(true) { 70 r.out(); 71 } 72 } 73 } 74 public class ProducerConsumerDemo { 75 76 public static void main(String[] args) { 77 78 Resource2 r = new Resource2(); 79 Producer pro = new Producer(r); 80 Consumer con = new Consumer(r); 81 82 Thread t0 = new Thread(pro); 83 Thread t1 = new Thread(pro); 84 Thread t2 = new Thread(con); 85 Thread t3 = new Thread(con); 86 87 t0.start(); 88 t1.start(); 89 t2.start(); 90 t3.start(); 91 } 92 93 }ProducerConsumerDemo