Repository navigation
Expand file tree
/
Copy pathThread8.java
More file actions
70 lines (57 loc) · 1.85 KB
/
Copy pathThread8.java
File metadata and controls
70 lines (57 loc) · 1.85 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
package thread;
import java.util.LinkedList;
import java.util.Queue;
public class Thread8 {
public static void main(String[] args) throws InterruptedException {
ProducerConsumer pc = new ProducerConsumer();
Thread thread1 = new Thread(() -> {
try {
pc.produce();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(() -> {
try {
pc.consume();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
class ProducerConsumer {
private Queue<Integer> queue = new LinkedList<>(); // сюда пишем и отсюда читаем
private final int LIMIT = 10; // вместимость очереди
private final Object lock = new Object(); // объект для управления блокировками потоков
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (lock) {
while (queue.size() == LIMIT) {
lock.wait();
}
queue.offer(value++);
lock.notify();
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (lock) {
while (queue.size() == 0) {
lock.wait();
}
int value = queue.poll();
System.out.println(value);
System.out.println("Queue size: " + queue.size());
lock.notify();
}
Thread.sleep(1000);
}
}
}