可阻塞队列
(1) 队列包含固定长度的队列和不固定长度的队列。
(2)什么是可阻塞队列,阻塞队列的作用与实际应用,阻塞队列的实现原理
ArrayBlockingQueue
看ArrayBlockingQueue类的帮助文档,其中有各个方法的区别对比的表格
只有put方法和take方法才具有阻塞功能
(3)用3个空间的队列来演示阻塞队列的功能和效果
(4)用两个具有1个空间的队列来实现同步通知的功能
(5)阻塞队列与Semaphore有些相似,单也不同。阻塞队列是一方存放数据,另一方释放数据,Semaphore
通常则是由同一方设置和释放信号量
package com.ronbay.thread.timer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueTest {
public static void main(String[] args) {
final BlockingQueue queue = new ArrayBlockingQueue(3);
for (int i = 0; i < 2; i++) {
new Thread(){
public void run(){
while(true){
try {
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "准备放数据");
queue.put(1);
System.out.println(Thread.currentThread().getName() + "已经放了数据" +
"队列目前有" + queue.size() + "个数据");
} catch (Exception e) {
// TODO: handle exception
}
}
}
}.start();
}
new Thread(){
public void run(){
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "准备取数据!");
queue.take();
System.out.println(Thread.currentThread().getName() + "已经取走数据" +
"队列目前有" + queue.size() +"个数据");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}