-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBoundedBufferProblem.java
More file actions
67 lines (63 loc) · 1.93 KB
/
BoundedBufferProblem.java
File metadata and controls
67 lines (63 loc) · 1.93 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
package multithreading;
/**
* @Author: Wenhang Chen
* @Description:生产者消费者
* @Date: Created in 17:00 4/4/2020
* @Modified by:
*/
public class BoundedBufferProblem {
// 当前值
private static int num = 0;
// 临界值
private final static int FULL = 10;
// 锁
private final static Object lock = new Object();
static class Producer implements Runnable {
@Override
public void run() {
int i = 0;
while (i < 5) {
synchronized (lock) {
// 先写不满足的时候wait住
while (num == FULL) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 满足的时候处理并且notifyAll
num++;
i++;
System.out.println(Thread.currentThread().getName() + " is producing");
lock.notifyAll();
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
int i = 0;
while (i < 5) {
synchronized (lock) {
while (num == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num--;
i++;
System.out.println(Thread.currentThread().getName() + " is consuming");
lock.notifyAll();
}
}
}
}
public static void main(String[] args) {
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}