jdk对Queue接口有自己的实现,在concurrent包中,子接口BlockingQueue定义了Queue所有的特性。
put和take是两个阻塞方法。当put值但队列已满时阻塞,take值但队列为空时阻塞。
以ArrayBlockQueue为例
1、生产者
public class Producer implements Runnable {
private BlockingQueue queue;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
queue.put(i);
System.out.println("我放进去了" + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.add(666);
System.out.println("我放进去了666");
}
}
public class Customer implements Runnable {
private BlockingQueue queue;
public Customer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
System.out.println("我拿出来了" + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3、输出
public class BlockingQueueExample {
public static void main(String[] args) {
BlockingQueue blockingQueue = new ArrayBlockingQueue(5);
Producer producer = new Producer(blockingQueue);
Customer customer = new Customer(blockingQueue);
new Thread(producer).start();
new Thread(customer).start();
}
}