-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerAndConsumer2.java
More file actions
93 lines (86 loc) · 2.55 KB
/
ProducerAndConsumer2.java
File metadata and controls
93 lines (86 loc) · 2.55 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
package common_problem.concurrent;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author JunjunYang
* @date 2020/4/28 14:47
*/
public class ProducerAndConsumer2<T> {
private int size;
private ReentrantLock lock=new ReentrantLock();
private Queue<T> queue=new LinkedList<>();
private Condition notFull=lock.newCondition();
private Condition notEmpty=lock.newCondition();
private static final Logger LOGGER= LoggerFactory.getLogger(ProducerAndConsumer2.class);
public static void main(String[] args) {
ProducerAndConsumer2<Integer> producerAndConsumer2=new ProducerAndConsumer2<Integer>(10);
ExecutorService executorService=Executors.newFixedThreadPool(2);
executorService.execute(()->{
for(int i=0;i<100;i++){
producerAndConsumer2.produce(i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executorService.execute(()->{
while(true) {
System.out.println(producerAndConsumer2.consume());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public ProducerAndConsumer2(int size) {
this.size=size;
}
/**
* 生产方法
* @param t
*/
public void produce(T t) {
lock.lock();
try {
while(queue.size()==size) {
notFull.await();
}
queue.add(t);
notEmpty.signal();
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
lock.unlock();
}
}
/**
* 消费方法
* @return
*/
public T consume() {
lock.lock();
try {
while(queue.isEmpty()) {
notEmpty.await();
}
T t=queue.poll();
notFull.signal();
return t;
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
lock.unlock();
}
}
}