码迷,mamicode.com
首页 > 其他好文 > 详细

黑马程序员-学习日记(生产者消费者实例)

时间:2014-12-11 20:37:02      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   on   div   

 

 1 class PCDemo 
 2 {
 3     public static void main(String[] args) 
 4     {
 5         Resource r = new Resource();
 6         Producer prd = new Producer(r);
 7         Consumer csu = new Consumer(r);
 8 
 9         Thread th0 = new Thread(prd);
10         Thread th1 = new Thread(prd);        
11         Thread th2 = new Thread(prd);
12         Thread th3 = new Thread(prd);
13 
14         Thread th4 = new Thread(csu);
15         Thread th5 = new Thread(csu);
16         Thread th6 = new Thread(csu);
17         Thread th7 = new Thread(csu);
18         th0.start();
19         th1.start();
20         th2.start();
21         th3.start();
22         th4.start();
23         th5.start();
24         th6.start();
25         th7.start();
26     }
27 }
28 
29 
30 class Resource
31 {
32     private String name;
33     private int count =1;
34     private boolean flag = false;
35 
36     public synchronized void set(String name)
37     {
38         if(flag)
39             try
40             {
41                 wait();
42             }
43             catch (Exception e)
44             {
45             }
46         this.name = name+"---"+count++;
47         System.out.println(Thread.currentThread().getName()+"生產"+this.name);
48         flag = true;
49         this.notify();
50     }
51     public synchronized void out()
52     {
53         if(!flag)
54             try
55             {
56                 wait();
57             }
58             catch (Exception e)
59             {
60             }
61         System.out.println(Thread.currentThread().getName()+"________消費"+this.name);
62         flag = false;
63         this.notify();
64     }
65 
66 }
67 
68 class Producer implements Runnable
69 {
70     private Resource res;
71     Producer(Resource res)
72     {
73         this.res = res;
74     }
75     public void run()
76     {
77         while(true)
78         {
79             res.set("物件");
80         }
81     }
82 }
83 
84 class Consumer implements Runnable
85 {
86     private Resource res;
87     Consumer(Resource res)
88     {
89         this.res = res;
90     }
91     public void run()
92     {
93         while(true)
94         {
95             res.out();
96         }
97     }
98 }

bubuko.com,布布扣

黑马程序员-学习日记(生产者消费者实例)

标签:style   blog   http   io   ar   color   sp   on   div   

原文地址:http://www.cnblogs.com/tozr/p/4158359.html

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