码迷,mamicode.com
首页 > 编程语言 > 详细

Java基础之多线程Stack类

时间:2019-08-08 18:48:35      阅读:100      评论:0      收藏:0      [点我收藏+]

标签: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 }

 

Java基础之多线程Stack类

标签:push   next   static   ack   current   mooc   vat   start   star   

原文地址:https://www.cnblogs.com/in-the-game-of-thrones/p/11322906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!