多线程Demo-ArrayBlockingQueue阻塞队列

package Thread;


import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;


public class BlockingQueueTest {
public static void main(String[] args) {
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
for(int i=0; i<10; i++){
new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "------放----------开始放数据,当前队列有"+queue.size());
queue.put(1);
System.out.println(Thread.currentThread().getName() + "------放----------完成放数据,当前队列有"+queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}.start();
}
for(int i=0; i<10; i++){
new Thread(){
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "------取----------开始取数据,当前队列有"+queue.size());
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
queue.take();
System.out.println(Thread.currentThread().getName() + "------取----------完成取数据,当前队列有"+queue.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}.start();
}
}
}


附录


线程安全队列另外还提供了
SynchronousQueue:其中每个插入操作必须等待另一个线程的对应移除操作 ,反之亦然。同步队列没有任何内部容量,甚至连一个队列的容量都没有。不能在同步队列上进行 peek,因为仅在试图要移除元素时,该元素才存在;除非另一个线程试图移除某个元素,否则也不能(使用任何方法)插入元素;也不能迭代队列,因为其中没有元素可用于迭代。队列的 是尝试添加到队列中的首个已排队插入线程的元素;如果没有这样的已排队线程,则没有可用于移除的元素并且 poll() 将会返回 null。对于其他 Collection 方法(例如 contains),SynchronousQueue 作为一个空 collection。此队列不允许 null 元素。 


队列更多查看:http://blog.youkuaiyun.com/ghsau/article/details/8108292

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值