BlockingQueue
(1)解决线程通信的问题。
(2)阻塞方法:put、take。
生产者消费者模式
(1)生产者:产生数据的线程。
(2)消费者:使用数据的线程。
实现类
(1)ArrayBlockingQueue
(2)LinkedBloockingQueue
(3)PriorityBlockingQueue、SynchronousQueue、DelayQueue等。
在BlockingQueueTests类里,
public static void main(String[] args) {
BlockingQueue queue = new ArrayBlockingQueue(10); //这个队列的容量是10
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start(); //设3个消费者
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()+"生产:"+queue.size());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue){
this.queue = queue;
}
@Override
public void run() {
try{
while (true){
Thread.sleep(new Random().nextInt(1000)); //用户产生数据或使用,一般有时间间隔,且时间间隔不确定
queue.take();
System.out.println(Thread.currentThread().getName()+"消费"+queue.size());
}
} catch (Exception e){
e.printStackTrace();
}
}
阻塞队列包含put方法,用于向队列中存入数据,当队列已满时,该方法将阻塞;阻塞队列包含take方法,用于从队列中获取数据,当队列已空时,该方法将阻塞。阻塞队列在生产者与消费者之间建立了缓冲,提高了系统的性能。