标签:push next static ack current mooc vat start star
使用Stack类实现生产者与消费者
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 java.util.Stack; 4 5 /** 6 * Stack类的使用 7 */ 8 public class StackTest { 9 public static void main(String[] args) { 10 Stack<Integer> s = new Stack<>(); 11 StackOOPS stackOOPS = new StackOOPS(s); 12 StackOOPC stackOOPC = new StackOOPC(s); 13 //开启两个生产者 14 new Thread(stackOOPC).start(); 15 new Thread(stackOOPS).start(); 16 //开启一个消费者 17 new Thread(stackOOPS).start(); 18 } 19 }
标签:push next static ack current mooc vat start star
原文地址:https://www.cnblogs.com/in-the-game-of-thrones/p/11322906.html