-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConditionTest.java
More file actions
123 lines (107 loc) · 2.66 KB
/
Copy pathConditionTest.java
File metadata and controls
123 lines (107 loc) · 2.66 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package four;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest<T> {
private int[] elements;
private Lock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition();
private int length = 0, addIndex = 0, removeIndex = 0;
public ConditionTest(int size) {
elements = new int[size];
}
public static void main(String[] args) throws InterruptedException {
@SuppressWarnings("rawtypes")
ConditionTest conditionTest = new ConditionTest(2);
Thread rs = new Thread(new Runnable() {
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
for (;;) {
String str = br.readLine();
int i = Integer.valueOf(str).intValue();
switch (i) {
case 1:
addThead(conditionTest);
continue;
case 2:
removeThead(conditionTest);
continue;
default:
continue;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
rs.start();
}
public static void addThead(ConditionTest conditionTest) {
Thread rs = new Thread(new Runnable() {
@Override
public void run() {
conditionTest.add(1);
}
});
rs.start();
}
public static void removeThead(ConditionTest conditionTest) {
Thread rs = new Thread(new Runnable() {
@Override
public void run() {
try {
conditionTest.remove();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
rs.start();
}
public void add(int value) {
lock.lock();
try {
while (length == elements.length) {
System.out.println("队列已满 请等待");
notFull.await();
}
System.out.println(value);
elements[addIndex] = value;
if (addIndex++ == elements.length) {
addIndex = 0;
}
length++;
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public int remove() throws InterruptedException {
lock.lock();
try {
while (0 == length) {
System.out.println("队列为空 请等待");
notFull.await();
}
int element = elements[removeIndex];
if (removeIndex++ == elements.length) {
removeIndex = 0;
}
length--;
notFull.signal();
return element;
} finally {
lock.unlock();
}
}
}