模拟生产者消费者(多条生产线多个消费者)

 1 import java.util.concurrent.ArrayBlockingQueue;
 2 import java.util.concurrent.BlockingQueue;
 3 import java.util.concurrent.locks.Lock;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 /**
 6  * 模拟生产者消费者(多条生产线多个消费者)
 7  * 仓库容量为10
 8  * 保证仓库充足量为5
 9  * @author trfizeng
10  *
11  */
12 public class ProcudectConcusrm {
13     public static int id = 0;
14     public static void main(String[] args) {
15         BlockingQueue<String> bQ = new ArrayBlockingQueue<String>(10);
16         Lock lockP = new ReentrantLock();
17         Lock lockC = new ReentrantLock();
18         for (int i = 0; i < 10; i++) {
19             new Thread(new Producer(bQ,lockP)).start();
20             new Thread(new Consumer(bQ,lockC)).start();
21         }
22     }
23     
24     public static class Producer implements Runnable{
25         BlockingQueue<String> bQ;
26         Lock lock;
27         public Producer(BlockingQueue<String> bQ,Lock lock) {
28             this.bQ = bQ;
29             this.lock = lock;
30         }
31         public void run() {
32             while (true) {
33                 try {
34                     String p = "产品" + ++id;
35                     lock.lock();
36                     if (5 >= bQ.size()) {
37                         bQ.put(p);
38                         System.out.println("放入产品:"+ p + ",当前库存:" + bQ.size());
39                         Thread.sleep(1500);
40                     }
41                 } catch (InterruptedException e) {
42                     e.printStackTrace();
43                 }finally{
44                     lock.unlock();
45                 }
46             }
47         }
48     }
49     
50     public static class Consumer implements Runnable{
51         BlockingQueue<String> bQ;
52         Lock lock;
53         public Consumer(BlockingQueue<String> bQ,Lock lock) {
54             this.bQ = bQ;
55             this.lock = lock;
56         }
57         public void run() {
58             while (true) {
59                 try {
60                     lock.lock();
61                     if (5 < bQ.size()) {
62                         System.out.println("取出产品:" + bQ.take() + ", 当前库存:" + bQ.size());
63                         Thread.sleep(1500);
64                     }
65                 } catch (InterruptedException e) {
66                     e.printStackTrace();
67                 }finally{
68                     lock.unlock();
69                 }
70             }
71         }
72     }
73 }
View Code

print:

放入产品:产品1,当前库存:1
放入产品:产品2,当前库存:2
放入产品:产品3,当前库存:3
放入产品:产品4,当前库存:4
放入产品:产品5,当前库存:5
放入产品:产品6,当前库存:6
取出产品:产品1, 当前库存:5
放入产品:产品16,当前库存:6
取出产品:产品2, 当前库存:5
放入产品:产品17,当前库存:6
取出产品:产品3, 当前库存:5
放入产品:产品7,当前库存:6
取出产品:产品4, 当前库存:5
取出产品:产品5, 当前库存:5
放入产品:产品8,当前库存:5
放入产品:产品20,当前库存:6
取出产品:产品6, 当前库存:5
放入产品:产品21,当前库存:6
取出产品:产品16, 当前库存:5
放入产品:产品22,当前库存:6
取出产品:产品17, 当前库存:5
放入产品:产品23,当前库存:6
取出产品:产品7, 当前库存:5
放入产品:产品9,当前库存:6
取出产品:产品8, 当前库存:5

posted on 2015-03-17 23:22  trfizeng  阅读(255)  评论(0编辑  收藏  举报

导航