-
Notifications
You must be signed in to change notification settings - Fork 0
/
生产消费模式
67 lines (63 loc) · 1.38 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
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
Product t = new Product(10); // 资源
new Producer(t).start();
new Consumer(t).start();
}
}
class Product {
private int maxSize;
private int index;
private LinkedList<Integer> v;
public Product(int n) {
maxSize = n;
index = 0;
v = new LinkedList<>();
}
synchronized void push() {
if (v.size() == maxSize) {
try {
wait();
} catch (Exception e) {}
}
System.out.println("生产了第" + (index+1) + "件产品");
v.add(index);
index++;
notify();
}
synchronized void pop() {
if(v.size() == 0) {
try {
wait();
} catch (Exception e) {}
}
int tmp = v.pop();
System.out.println("消费了第" + (tmp+1) + "件产品");
notify();
}
}
class Producer extends Thread {
private Product t;
public Producer(Product t) {
this.t = t;
}
@Override
public void run() {
while(true) {
t.push();
}
}
}
class Consumer extends Thread {
private Product t;
public Consumer(Product t) {
this.t = t;
}
@Override
public void run() {
while(true) {
t.pop();
}
}
}