多个生产者/一个消费者:
1 /** 2 * 生产者 3 */ 4 public class P { 5 6 private MyStack stack; 7 8 public P(MyStack stack) { 9 this.stack = stack; 10 } 11 12 public void pushService() { 13 stack.push(); 14 } 15 }
1 /** 2 * 消费者 3 */ 4 public class C { 5 6 private MyStack stack; 7 8 public C(MyStack stack) { 9 this.stack = stack; 10 } 11 12 public void popService() { 13 System.out.println("pop = " + stack.pop()); 14 } 15 }
1 /** 2 * 模拟栈 3 */ 4 public class MyStack { 5 private List<Object> list = new ArrayList<>(); 6 7 public synchronized void push() { 8 try { 9 while(list.size() == 1) { 10 this.wait(); 11 } 12 list.add(""+Math.random()); 13 this.notifyAll(); 14 System.out.println("push:" + list.size()); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 } 19 20 public synchronized String pop() { 21 String value = ""; 22 try { 23 while(list.size() == 0) { 24 System.out.println("pop 操作中:" + Thread.currentThread().getName() + "wait状态"); 25 this.wait(); 26 } 27 value = ""+list.get(0); 28 list.remove(0); 29 this.notifyAll(); 30 System.out.println("pop:" + list.size()); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 return value; 35 } 36 }
1 /** 2 * 生产者线程 3 */ 4 public class P_Thread extends Thread { 5 6 private P p; 7 8 public P_Thread(P p) { 9 this.p = p; 10 } 11 12 @Override 13 public void run() { 14 while (true) { 15 p.pushService(); 16 } 17 } 18 }
1 /** 2 * 消费者线程 3 */ 4 public class C_Thread extends Thread { 5 6 private C c; 7 8 public C_Thread(C c) { 9 this.c = c; 10 } 11 12 @Override 13 public void run() { 14 while (true) { 15 c.popService(); 16 } 17 } 18 }
1 /** 2 * 测试类 3 */ 4 public class Run { 5 6 public static void main(String[] args) { 7 MyStack stack = new MyStack(); 8 P p1 = new P(stack); 9 P p2 = new P(stack); 10 P p3 = new P(stack); 11 C c1 = new C(stack); 12 13 P_Thread pThread1 = new P_Thread(p1); 14 P_Thread pThread2 = new P_Thread(p2); 15 P_Thread pThread3 = new P_Thread(p3); 16 C_Thread cThread1 = new C_Thread(c1); 17 18 pThread1.start(); 19 pThread2.start(); 20 pThread3.start(); 21 cThread1.start(); 22 } 23 }
运行结果如下: