forked from fengshao0907/JavaCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepot.java
More file actions
87 lines (79 loc) · 2.64 KB
/
Copy pathDepot.java
File metadata and controls
87 lines (79 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.javaCore.concurrency.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Depot {
private int depotSize; // �ֿ��С
private Lock lock; // ��ռ��
private int capaity; // �ֿ�����
private Condition fullCondition;
private Condition emptyCondition;
public Depot() {
this.depotSize = 0;
this.lock = new ReentrantLock();
this.capaity = 15;
this.fullCondition = lock.newCondition();
this.emptyCondition = lock.newCondition();
}
/**
* ��Ʒ���
*
* @param value
*/
public void put(int value) {
lock.lock();
try {
int left = value;
while (left > 0) {
// �������ʱ��������ߡ��ȴ�����ߡ����
while (depotSize >= capaity) {
fullCondition.await();
}
// ��ȡʵ�����������Ԥ�ƿ�棨�ֿ����п�� + ��������� > �ֿ����� ? �ֿ����� - �ֿ����п�� : �������
// depotSize left capaity capaity - depotSize left
int inc = depotSize + left > capaity ? capaity - depotSize
: left;
depotSize += inc;
left -= inc;
System.out.println(Thread.currentThread().getName()
+ "----Ҫ�������: " + value + ";;ʵ�����������" + inc
+ ";;�ֿ����������" + depotSize + ";;û�����������" + left);
// ֪ͨ����߿��������
emptyCondition.signal();
}
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
/**
* ��Ʒ����
*
* @param value
*/
public void get(int value) {
lock.lock();
try {
int left = value;
while (left > 0) {
// �ֿ��ѿգ�������ߡ��ȴ�����ߡ�������
while (depotSize <= 0) {
emptyCondition.await();
}
// ʵ����� �ֿ������� < Ҫ��ѵ����� ? �ֿ������� : Ҫ��ѵ�����
int dec = depotSize < left ? depotSize : left;
depotSize -= dec;
left -= dec;
System.out.println(Thread.currentThread().getName()
+ "----Ҫ��ѵ�������" + value + ";;ʵ����ѵ�����: " + dec
+ ";;�ֿ��ִ�������" + depotSize + ";;�ж��ټ���Ʒû����ѣ�" + left);
// ֪ͨ����߿��������
fullCondition.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}