消息量很大,所以要TB数量级
接下来通过一个实例进一步说明:
在test包下新建BlockingQueueTests
package com.nowcoder.community;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueTests {
public static void main(String[] args) {
BlockingQueue queue = new ArrayBlockingQueue(10);//实例化阻塞队列
new Thread(new Producer(queue)).start();//建立生产者线程 new Thread,线程体是new Producer(queue),建好后启动
new Thread(new Consumer(queue)).start();//建立消费者线程 new Thread,线程体是new Producer(queue),建好后启动
new Thread(new Consumer(queue)).start();//建立消费者线程 new Thread,线程体是new Producer(queue),建好后启动
new Thread(new Consumer(queue)).start();//建立消费者线程 new Thread,线程体是new Producer(queue),建好后启动
}
}
class Producer implements Runnable {//声明一个生产者类
private BlockingQueue<Integer> queue;//阻塞队列里面存着 Integer
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}//构建构造器
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {//循环100次
Thread.sleep(20);//停顿20毫秒
queue.put(i);//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));//消费时间间隔不需要写死。0-1000之间的一个数,大概率比20大
queue.take();
System.out.println(Thread.currentThread().getName() + "消费:" + queue.size());//当前消费者线程名字
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试:
2
看头和尾就能看出一些问题:
生产者每隔20s就能生产一个数据,更快。
因此很快就生产了十个数据
消费完一个变为9
这时,队列不满了,继续生成一个 ,变为10