一个生产者/一个消费者:
1 /** 2 * 生产者 3 */ 4 public class P { 5 private MyStack stack; 6 7 public P(MyStack stack) { 8 this.stack = stack; 9 } 10 11 public void pushService() { 12 stack.push(); 13 } 14 }
1 /** 2 * 消费者 3 */ 4 public class C { 5 private MyStack stack; 6 7 public C(MyStack stack) { 8 this.stack = stack; 9 } 10 11 public void popService() { 12 System.out.println("pop = " + stack.pop()); 13 } 14 }
1 /** 2 * 生产者线程 3 */ 4 public class P_Thread extends Thread { 5 private P p; 6 7 public P_Thread(P p) { 8 this.p = p; 9 } 10 11 @Override 12 public void run() { 13 while (true) { 14 p.pushService(); 15 } 16 } 17 }
1 /** 2 * 消费者线程 3 */ 4 public class C_Thread extends Thread { 5 private C c; 6 7 public C_Thread(C c) { 8 this.c = c; 9 } 10 11 @Override 12 public void run() { 13 while (true) { 14 c.popService(); 15 } 16 } 17 }
1 /** 2 * 模拟栈List 3 */ 4 public class MyStack { 5 private List<Object> list = new ArrayList<>(); 6 7 //压栈 8 public synchronized void push() { 9 try { 10 while(list.size() == 1) { 11 this.wait(); 12 } 13 list.add(""+Math.random()); 14 this.notify(); 15 System.out.println("push:" + list.size()); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 21 //弹栈 22 public synchronized String pop() { 23 String value = ""; 24 try { 25 while(list.size() == 0) { 26 this.wait(); 27 } 28 value = ""+list.get(0); 29 list.remove(0); 30 this.notify(); 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 Run { 5 6 public static void main(String[] args) { 7 MyStack stack = new MyStack(); 8 //创建生产和消费者 9 P p = new P(stack); 10 C c = new C(stack); 11 12 //创建生产和消费者线程 13 P_Thread pThread = new P_Thread(p); 14 C_Thread cThread = new C_Thread(c); 15 16 //启动 17 pThread.start(); 18 cThread.start(); 19 } 20 }
运行结果如下: