阻塞队列,如果指定初始大小,在达到最大时添加将阻塞,同理队列中没有东西,在取的时候将阻塞,阻塞队列类均实现BlockingQueue接口,根据其原理实现:生产一个消费一个(代码跑起来你就明白了)
下面是我一个初学者的笔记,大神请绕道
package net.youqu;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class QueueTest {
private BlockingQueue<String> queue = new LinkedBlockingQueue<>(1);
private volatile boolean flag = true;
public void produce() {
try {
int index = new Random().nextInt(10);
queue.put("" + index);
System.out.println("生产了:" + index);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String consumer() {
try {
return queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
class Thread1 implements Runnable {
@Override
public void run() {
while (flag) {
System.out.println("我消费了:" + consumer());
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while (flag) {
produce();
}
}
}
public static void main(String[] args) throws Exception{
QueueTest qt = new QueueTest();
new Thread(qt.new Thread2()).start();
new Thread(qt.new Thread1()).start();
Thread.sleep(10);
qt.flag = false;
}
}