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

JAVA_线程同步_生产者消费者问题

时间:2015-05-14 00:52:31      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

 

 1 public class ProducerConsumer {
 2     public static void main(String[] args) {
 3         SyncStack ss = new SyncStack();
 4         Producer p = new Producer(ss);
 5         Consumer c = new Consumer(ss);
 6         new Thread(p).start();
 7         new Thread(p).start();
 8         new Thread(p).start();
 9         new Thread(c).start();
10     }
11 }
12 
13 class WoTou {
14     int id; 
15     WoTou(int id) {
16         this.id = id;
17     }
18     public String toString() {
19         return "WoTou : " + id;
20     }
21 }
22 
23 class SyncStack {
24     int index = 0;
25     WoTou[] arrWT = new WoTou[6];
26     
27     public synchronized void push(WoTou wt) {
28         while(index == arrWT.length) {
29             try {
30                 this.wait();
31             } catch (InterruptedException e) {
32                 e.printStackTrace();
33             }
34         }
35         this.notifyAll();
36         arrWT[index] = wt;
37         index ++;
38     }
39     
40     public synchronized WoTou pop() {
41         while(index == 0) {
42             try {
43                 this.wait();
44             } catch (InterruptedException e) {
45                 e.printStackTrace();
46             }
47         }
48         this.notifyAll();
49         index--;
50         return arrWT[index];
51     }
52 }
53 
54 class Producer implements Runnable {
55     SyncStack ss = null;
56     Producer(SyncStack ss) {
57         this.ss = ss;
58     }
59     
60     public void run() {
61         for(int i=0; i<20; i++) {
62             WoTou wt = new WoTou(i);
63             ss.push(wt);
64 System.out.println("生产了:" + wt);
65             try {
66                 Thread.sleep((int)(Math.random() * 200));
67             } catch (InterruptedException e) {
68                 e.printStackTrace();
69             }            
70         }
71     }
72 }
73 
74 class Consumer implements Runnable {
75     SyncStack ss = null;
76     Consumer(SyncStack ss) {
77         this.ss = ss;
78     }
79     
80     public void run() {
81         for(int i=0; i<60; i++) {
82             WoTou wt = ss.pop();
83 System.out.println("消费了: " + wt);
84             try {
85                 Thread.sleep((int)(Math.random() * 1000));
86             } catch (InterruptedException e) {
87                 e.printStackTrace();
88             }            
89         }
90     }
91 }

 

JAVA_线程同步_生产者消费者问题

标签:

原文地址:http://www.cnblogs.com/roger-h/p/4502192.html

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