Java多线程系列--“JUC锁”02之 互斥锁ReentrantLock(二)

2014-11-24 03:11:13 · 作者: · 浏览: 4
ume(int val) {
49 lock.lock();
50 try {
51 // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)
52 int left = val;
53 while (left > 0) {
54 // 库存为0时,等待“生产者”生产产品。
55 while (size <= 0)
56 emptyCondtion.await();
57 // 获取“实际消费的数量”(即库存中实际减少的数量)
58 // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;
59 // 否则,“实际消费量”=“客户要消费的数量”。
60 int dec = (size
61 size -= dec;
62 left -= dec;
63 System.out.printf("%s consume(%3d) <-- left=%3d, dec=%3d, size=%3d\n",
64 Thread.currentThread().getName(), val, left, dec, size);
65 fullCondtion.signal();
66 }
67 } catch (InterruptedException e) {
68 } finally {
69 lock.unlock();
70 }
71 }
72
73 public String toString() {
74 return "capacity:"+capacity+", actual size:"+size;
75 }
76 };
77
78 // 生产者
79 class Producer {
80 private Depot depot;
81
82 public Producer(Depot depot) {
83 this.depot = depot;
84 }
85
86 // 消费产品:新建一个线程向仓库中生产产品。
87 public void produce(final int val) {
88 new Thread() {
89 public void run() {
90 depot.produce(val);
91 }
92 }.start();
93 }
94 }
95
96 // 消费者
97 class Customer {
98 private Depot depot;
99
100 public Customer(Depot depot) {
101 this.depot = depot;
102 }
103
104 // 消费产品:新建一个线程从仓库中消费产品。
105 public void consume(final int val) {
106 new Thread() {
107 public void run() {
108 depot.consume(val);
109 }
110 }.start();
111 }
112 }
113
114 public class LockTest3 {
115 public static void main(String[] args) {
116 Depot mDepot = new Depot(100);
117 Producer mPro = new Producer(mDepot);
118 Customer mCus = new Customer(mDepot);
119
120 mPro.produce(60);
121 mPro.produce(120);
122 mCus.consume(90);
123 mCus.consume(150);
124 mPro.produce(110);
125 }
126 }
复制代码