生产者消费者(阻塞队列)
作者:互联网
阻塞队列实现等待唤醒机制
BlockingQueue 的核心方法:
put(anObect) 将参数放入队列,如果放不进去会阻塞。
take():取出第一个数据,取不到会阻塞。
常见BlockingQueue:
ArrayBlockingQueue:底层是数组,有界。
LinkedBlockingQueue:底层是链表,无界。但不是真正的无界,最大为int的最大值
阻塞队列继承结构
Iterabe-> Colection -> Queue ->BlockingQueue -> ArrBlockingQueue
-> LinkedBlockingQueue
package threadDemo15;
import java.util.concurrent.ArrayBlockingQueue;
public class Coodie extends Thread{
private ArrayBlockingQueue<String> list;
public Coodie(ArrayBlockingQueue<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
try {
list.put("汉堡包");
System.out.println("厨师放了一个汉堡包");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package threadDemo15;
import java.util.concurrent.ArrayBlockingQueue;
public class Cooker extends Thread{
private ArrayBlockingQueue<String> list;
public Cooker(ArrayBlockingQueue<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
try {
String take = list.take();
System.out.println("吃货从队列中获取了"+take);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package threadDemo15;
import java.util.concurrent.ArrayBlockingQueue;
public class Demo {
// 阻塞队列的基本用法
/**
* @param args
* @throws InterruptedException
*/
// 创建阻塞队列的对象,容量为1
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ArrayBlockingQueue<String> list = new ArrayBlockingQueue<String>(1);
Cooker c = new Cooker(list);
Coodie f = new Coodie(list);
c.start();
f.start();
}
}
标签:Cooker,队列,list,阻塞,生产者,ArrayBlockingQueue,public 来源: https://blog.csdn.net/baidu_31573795/article/details/122774578