Repository navigation
Expand file tree
/
Copy pathThread6.java
More file actions
78 lines (63 loc) · 2.33 KB
/
Copy pathThread6.java
File metadata and controls
78 lines (63 loc) · 2.33 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
package thread;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Thread6 {
// потокобезопасная очередь FIFO
// имеет вместимость 10
private static BlockingQueue<Integer> queue = new ArrayBlockingQueue(10);
public static void main(String[] args) throws InterruptedException {
// поток 1 добавляет значения в очередь
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
produce();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
// потом 2 забирает значения из очереди
Thread thread2 = new Thread(() -> {
try {
consumer();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
/**
* Продюсер публикует в очередь новые значения
*
* @throws InterruptedException
*/
private static void produce() throws InterruptedException {
Random rand = new Random();
while (true) {
Thread.sleep(200);
// добавим задание в очередь, если это позволяет вместимость ArrayBlockingQueue
queue.put(rand.nextInt(100));
}
}
/**
* Консьюмер забирает готовые результаты из очереди
* @throws InterruptedException
*/
private static void consumer() throws InterruptedException {
Random rand = new Random();
while (true) {
Thread.sleep(110);
// забирает из очереди задание
// забираем чуть медленнее или так же, как пополняем очередь
if (rand.nextInt(10) > 4) {
System.out.println(queue.take());
}
System.out.println("Queue size: " + queue.size());
}
}
}