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

JAVA平时练习

时间:2015-05-26 18:02:23      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

生产者与消费者:

技术分享
 1 public class ProducerConsumer {
 2     public static void main(String[] args) {
 3         Basket bs=new Basket();
 4         Producer p=new Producer(bs);
 5         Consumer stu1=new Consumer("张东",bs);
 6         Consumer stu2=new Consumer("王强",bs);
 7         Consumer stu3=new Consumer("赵璐",bs);
 8         new Thread(p).start();
 9         new Thread(stu1).start();
10         new Thread(stu2).start();
11         new Thread(stu3).start();
12     }
13 }
14 
15 class ManTou {
16     int id;
17     ManTou(int id){
18         this.id=id;
19     }
20     public String toString(){
21         return  "第"+id+"个馒头" ;
22     }
23 }
24 
25 class Basket {
26     int index = 0;
27     ManTou[] mt = new ManTou[10];
28 
29     public synchronized void push(ManTou ton) {
30         while (index == mt.length) {
31             try {
32                 this.wait();
33             } catch (InterruptedException e) {
34                 e.printStackTrace();
35             }
36         }
37         this.notifyAll();
38         mt[index] = ton;
39         index++;
40     }
41     public synchronized ManTou pop() {
42         while (index == 0) {
43             try {
44                 this.wait();
45             } catch (InterruptedException e) {
46                 e.printStackTrace();
47             }
48         }
49         this.notifyAll();
50         index--;
51         return mt[index];
52     }
53     
54 }
55 
56 class Producer implements Runnable{
57     Basket bs= null;
58     Producer(Basket bs){
59         this.bs=bs;
60     }
61     public void run(){
62         for(int i=1;i<=15;i++){
63             ManTou mt=new ManTou(i);
64             bs.push(mt);
65             System.out.println("李师傅生产了"+mt.toString());
66             try{
67                 Thread.sleep((int)(Math.random()*100));
68             }catch(InterruptedException e){
69                 e.printStackTrace();
70             }
71         }
72     }
73     
74 }
75 
76 
77 class Consumer implements Runnable{
78     Basket bs= null;
79     String name;
80     Consumer(String stu,Basket bs){
81         this.bs=bs;
82         name=stu;
83     }
84     public void run(){
85         for(int i=1;i<=5;i++){
86             ManTou mt=bs.pop();
87             System.out.println(name+"消费了"+mt.toString());
88             try{
89                 Thread.sleep((int)(Math.random()*1000));
90             }catch(InterruptedException e){
91                 e.printStackTrace();
92             }
93         }
94     }
95     
96 }
View Code

 

JAVA平时练习

标签:

原文地址:http://www.cnblogs.com/cangqiongbingchen/p/4530952.html

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