-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPCTest.java
More file actions
118 lines (102 loc) · 2.14 KB
/
Copy pathPCTest.java
File metadata and controls
118 lines (102 loc) · 2.14 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
package java_base;
class MyStack{
static final int MAX = 5;
private int[] buffer = new int[MAX];
private int put_i = 0;
private int get_i = 0;
private int size = 0;
public synchronized void push(int i) {
// TODO Auto-generated method stub
while(size == MAX) {
System.out.println("缓存区满,不能放入,请等待...");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
}
buffer[put_i] = i;
System.out.println("放入产品:" + buffer[put_i] + "到第" + put_i + "格");
size ++;
if(put_i == MAX-1)
{
put_i = 1;
}else {
put_i ++;
}
notify();
}
public synchronized int pop() {
while(size == 0)
{
System.out.println("缓冲区空,不能取,请等待...");
try {
wait();
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
size --;
System.out.printf("%80s\n", "取出产品" + buffer[get_i]);
if(get_i == MAX -1)
{
get_i = 1;
}else {
get_i ++;
}
return buffer[get_i];
// TODO Auto-generated method stub
}
}
class Producer extends Thread{
private MyStack buffer;
public Producer(MyStack buffer) {
// TODO Auto-generated constructor stub
this.buffer = buffer;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
for(int i = 0;; i++)
{
sleep((long) Math.random() * 1000 + 500);
buffer.push(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread{
private MyStack buffer;
public Consumer(MyStack buffer) {
// TODO Auto-generated constructor stub
this.buffer = buffer;
}
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
try {
while(true) {
i = buffer.pop();
sleep((long)Math.random() * 1000 + 500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class PCTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack buffer = new MyStack();
new Consumer(buffer).start();
new Consumer(buffer).start();
new Consumer(buffer).start();
new Producer(buffer).start();
}
}