生产者与消费者-1:N-基于list
一个生产者/多个消费者:
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 6 private List<Object> list = new ArrayList<>(); 7 8 public synchronized void push() { 9 try { 10 while(list.size() == 1) { 11 this.wait(); 12 } 13 list.add(""+Math.random()); 14 this.notifyAll(); 15 System.out.println("push:" + list.size()); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 21 public synchronized String pop() { 22 String value = ""; 23 try { 24 while(list.size() == 0) { 25 System.out.println("pop 操作中:" + Thread.currentThread().getName() + "wait状态"); 26 this.wait(); 27 } 28 value = ""+list.get(0); 29 list.remove(0); 30 this.notifyAll(); 31 System.out.println("pop:" + list.size()); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 return value; 36 } 37 }
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 //一个生产者 9 P p = new P(stack); 10 //多个消费者 11 C c1 = new C(stack); 12 C c2 = new C(stack); 13 C c3 = new C(stack); 14 15 //一个生产者线程 16 P_Thread pThread = new P_Thread(p); 17 //多个消费者线程 18 C_Thread cThread1 = new C_Thread(c1); 19 C_Thread cThread2 = new C_Thread(c2); 20 C_Thread cThread3 = new C_Thread(c3); 21 22 //启动 23 pThread.start(); 24 cThread1.start(); 25 cThread2.start(); 26 cThread3.start(); 27 } 28 }
运行结果如下: