-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTestProductorAndConsumer2.java
107 lines (91 loc) · 1.97 KB
/
TestProductorAndConsumer2.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.jucday01;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 生产者和消费者案例
*/
public class TestProductorAndConsumer2 {
public static void main(String[] args) {
Clerk2 clerk=new Clerk2();
Productor2 pro=new Productor2(clerk);
Consumer2 con=new Consumer2(clerk);
new Thread(pro,"生产者A").start();
new Thread(con,"消费者A").start();
new Thread(pro,"生产者B").start();
new Thread(con,"消费者B").start();
}
}
class Clerk2{
private int product=10;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void get() {
lock.lock();
try {
while(product>=20) {
System.out.println("产品已满");
try {
condition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ ++product);
condition.signalAll();
}finally {
lock.unlock();
}
}
public void sale() {
lock.lock();
try {
while(product<=0) {
System.out.println("产品缺货");
try {
condition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ --product);
condition.signalAll();
}
finally {
lock.unlock();
}
}
}
class Productor2 implements Runnable{
private Clerk2 clerk;
public Productor2(Clerk2 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 Consumer2 implements Runnable{
private Clerk2 clerk;
public Consumer2(Clerk2 clerk) {
this.clerk=clerk;
}
@Override
public void run() {
for(int i=0;i<20;i++) {
clerk.sale();
}
}
}