阻塞队列-生产者消费者思想
BlockingQueue
- 解决线程通信的问题
- 阻塞方法:put、take
生产者消费者模式 - 生产者:产生数据的线程
- 消费者:使用数据的线程
实现类 - ArrayBlockingQueue
- LinkedBlockingQueue
- PriorityBlockingQueue、SynchronousQueue等
示例:
public class BlockingQueueTests {
public static void main(String[] args) {
BlockingQueue queue = new ArrayBlockingQueue(10);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
new Thread(new Consumer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(20);
queue.put(i);
System.out.println(Thread.currentThread().getName() + " 生产了 " + i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(new Random().nextInt(1000));
Integer j = queue.take();
System.out.println(Thread.currentThread().getName() + " 消费了 " + j);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}结果:

查看19道真题和解析