-
Notifications
You must be signed in to change notification settings - Fork 3
/
TestProductorAndConsumer.java
85 lines (75 loc) · 1.6 KB
/
TestProductorAndConsumer.java
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
package com.jucday01;
/*
* 生产者和消费者案例
*/
public class TestProductorAndConsumer {
public static void main(String[] args) {
Clerk clerk=new Clerk();
Productor pro=new Productor(clerk);
Consumer con=new Consumer(clerk);
new Thread(pro,"生产者A").start();
new Thread(con,"消费者A").start();
new Thread(pro,"生产者B").start();
new Thread(con,"消费者B").start();
}
}
class Clerk{
private int product=10;
public synchronized void get() {
while(product>=20) {
System.out.println("产品已满");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ ++product);
this.notifyAll();
}
public synchronized void sale() {
while(product<=0) {
System.out.println("产品缺货");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ --product);
this.notifyAll();
}
}
class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk) {
super();
this.clerk = clerk;
}
@Override
public void run() {
for(int i=0;i<20;i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.get();
}
}
}
class Consumer implements Runnable{
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk=clerk;
}
@Override
public void run() {
for(int i=0;i<20;i++) {
clerk.sale();
}
}
}