阻塞队列实现等待唤醒机制
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
public Coodie(ArrayBlockingQueue
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
public Cooker(ArrayBlockingQueue
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 {
// 阻塞队列的基本用法
// 创建阻塞队列的对象,容量为1
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ArrayBlockingQueue
Cooker c = new Cooker(list);
Coodie f = new Coodie(list);
c.start();
f.start();
}
}