Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
55 lines (48 loc) · 1.61 KB

File metadata and controls

55 lines (48 loc) · 1.61 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package thread;
import java.util.concurrent.ArrayBlockingQueue;
/**
* Created by yahier on 10/29/18.
*
* 生产者-消费者的解决方案 ArrayBlockingQueue.
* 1)测试发现,如果线程不sleep 基本上是写满-取完-写满-取完的逻辑,如果sleep(1000),基本上是有消息马上就被读完了
*/
public class BlockingQueueTest {
private int size = 20;
//一旦创建,容量不会改变
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(size, false);
public static void main(String[] args) {
BlockingQueueTest test = new BlockingQueueTest();
Producer producer = test.new Producer();
Consumer consumer = test.new Consumer();
producer.start();
consumer.start();
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
try {
//从阻塞队列中取出一个元素
queue.take();
System.out.println("————————" + queue.size());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
while (true) {
try {
//向阻塞队列中插入一个元素
queue.put(1);
System.out.println("........" + queue.size());
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.