Use Stack class implements producers and consumers
1 package com.imooc.demo; 2 3 import java.util.Random; 4 import java.util.Stack; 5 //生产者 6 public class StackOOPS implements Runnable{ 7 8 private Stack<Integer> stack; 9 public StackOOPS(Stack<Integer> stack){ 10 this.stack = stack; 11 } 12 13 @Override 14 public void run() { 15 Random random = new Random(); 16 while (true){ 17 if (stack.size() < 6){ 18 int num = random.nextInt(); 19 stack.push(num); 20 System.out.println(Thread.currentThread().getName()+"生产了:"+num); 21 }else{ 22 try { 23 Thread.sleep(100); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } 27 } 28 } 29 } 30 }
1 package com.imooc.demo; 2 3 import java.util.Stack; 4 //消费者 5 public class StackOOPC implements Runnable { 6 7 private Stack<Integer> stack; 8 9 public StackOOPC(Stack<Integer> stack){ 10 this.stack = stack; 11 } 12 @Override 13 public void run() { 14 while (true){ 15 if (stack.size() > 0){ 16 Integer num = stack.pop(); 17 System.out.println(Thread.currentThread().getName()+"消费了:"+num); 18 }else{ 19 try { 20 Thread.sleep(200); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 } 25 } 26 } 27 }
. 1 Package com.imooc.demo; 2 . 3 Import the java.util.Stack; . 4 . 5 / ** . 6 * class used Stack . 7 * / . 8 public class StackTest { . 9 public static void main (String [] args) { 10 Stack <Integer> = S new new Stack <> (); . 11 StackOOPS stackOOPS = new new StackOOPS (S); 12 is StackOOPC stackOOPC = new new StackOOPC (S); 13 is // open two producers 14 new newThe Thread (stackOOPC) .start (); 15 new new the Thread (stackOOPS) .start (); 16 // Open a consumer . 17 new new the Thread (stackOOPS) .start (); 18 is } . 19 }