阻塞队列

-
BlockingQueue的核心方法:
- put(anObject): 将参数放入队列,如果放不进去会阻塞
- take(): 取出第一个数据,取不到会阻塞
-
常见的BlockingQueue
- ArrayBlockingQueue:底层是数组,有界
- LinkedBlockingQueue:底层是链表,无界。但不是真正的无界,最大为int的最大值
阻塞队列的基本写法
package com.cmy.threaddemo11;
import java.util.concurrent.ArrayBlockingQueue;
/**
* @author 陈明勇
*/
public class Demo {
public static void main(String[] args) throws InterruptedException {
// 阻塞队列的基本用法
// 创建阻塞队列的对象,容量为1
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(1);
// 存储元素
arrayBlockingQueue.put("披萨");
// 取元素
System.out.println(arrayBlockingQueue.take());
// 取不到第二个元素,会阻塞
System.out.println(arrayBlockingQueue.take());
}
}
ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(1); 传入的参数1表示容量为1
实现等待唤醒机制
-
生产者
package com.cmy.threaddemo12; import java.util.concurrent.ArrayBlockingQueue; /** * @author 陈明勇 */ public class Cooker extends Thread{ private ArrayBlockingQueue<String> arrayBlockingQueue; public Cooker(ArrayBlockingQueue<String> arrayBlockingQueue) { this.arrayBlockingQueue = arrayBlockingQueue; } @Override public void run() { while (true) { try { arrayBlockingQueue.put("披萨"); System.out.println("厨师放了一个披萨"); } catch (InterruptedException e) { e.printStackTrace(); } } } } -
消费者
package com.cmy.threaddemo12; import java.util.concurrent.ArrayBlockingQueue; /** * @author 陈明勇 */ public class Foodie extends Thread{ private ArrayBlockingQueue<String> arrayBlockingQueue; public Foodie(ArrayBlockingQueue<String> arrayBlockingQueue) { this.arrayBlockingQueue = arrayBlockingQueue; } @Override public void run() { String take = null; while (true) { try { take = arrayBlockingQueue.take(); System.out.println("吃货从队列中获取了一个" + take); } catch (InterruptedException e) { e.printStackTrace(); } } } } -
测试类
package com.cmy.threaddemo12; import java.util.concurrent.ArrayBlockingQueue; /** * @author 陈明勇 */ public class Demo { public static void main(String[] args) { // 创建阻塞队列 ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(1); // 创建线程并开启 Cooker cooker = new Cooker(arrayBlockingQueue); Foodie foodie = new Foodie(arrayBlockingQueue); cooker.start(); foodie.start(); } } Foodie foodie = new Foodie(arrayBlockingQueue); cooker.start(); foodie.start(); } }

1908

被折叠的 条评论
为什么被折叠?



