今天我们通过实例来学习一下BlockingQueue的用法。梦想,可以天花乱坠,理想,是我们一步一个脚印踩出来的坎坷道路。

BlockingQueue的实例

官方文档上的对于BlockingQueue的说明:

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

如果BlockQueue是空的,从BlockingQueue取东西的操作将会被阻断进入等待状态,直到BlockingQueue进了东西才会被唤醒.同样,如果BlockingQueue是满的,任何试图往里存东西的操作也会被阻断进入等待状态,直到BlockingQueue里有空间才会被唤醒继续操作

一、BlockingQueue的简单使用

package com.linux.huhx.concurreny;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit; public class BlockingQueueTest {
public static void main(String[] args) {
BlockingQueue q = new LinkedBlockingDeque();
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
} static class Producer implements Runnable {
private final BlockingQueue<String> queue;
Producer(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 4; i++) {
try {
queue.put("producer" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} static class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
for (int i = 0; i < 2; i++) {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(2000));
System.out.println(queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

运行的结果如下:使用put和take方法,打印的结果是固定的。它会阻塞。

producer0
producer1
producer2
producer3

二、ArrayBlockIngQueue的使用

package com.linux.thread.thread;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;

public class ArrayBlockQueueTest {
@Test
public void put() {
try {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
queue.put("huhx");
queue.put("linux");
queue.put("ll");
System.out.println("size: " + queue.size());
System.out.println("begin: " + System.currentTimeMillis());
queue.put("tomhu"); // 阻塞
System.out.println("end: " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
} @Test
public void get() {
try {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
System.out.println("begin: " + System.currentTimeMillis());
System.out.println(queue.take()); // 阻塞
System.out.println("end: " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

友情链接

java高级---->Thread之BlockingQueue的使用的更多相关文章

  1. java高级---->Thread之ScheduledExecutorService的使用

    ScheduledExecutorService的主要作用就是可以将定时任务与线程池功能结合使用.今天我们来学习一下ScheduledExecutorService的用法.我们都太渺小了,那么容易便湮 ...

  2. java高级---->Thread之ExecutorService的使用

    今天我们通过实例来学习一下ExecutorService的用法.我徒然学会了抗拒热闹,却还来不及透悟真正的冷清. ExecutorService的简单实例 一.ExecutorService的简单使用 ...

  3. java高级---->Thread之Phaser的使用

    Phaser提供了动态增parties计数,这点比CyclicBarrier类操作parties更加方便.它是jdk1.7新增的类,今天我们就来学习一下它的用法.尘埃落定之后,回忆别来挑拨. Phas ...

  4. java高级---->Thread之CompletionService的使用

    CompletionService的功能是以异步的方式一边生产新的任务,一边处理已完成任务的结果,这样可以将执行任务与处理任务分离开来进行处理.今天我们通过实例来学习一下CompletionServi ...

  5. java高级---->Thread之CyclicBarrier的使用

    CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).今天我们就学习一下CyclicBarrier的用法. Cycl ...

  6. java高级---->Thread之Exchanger的使用

    Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据.今天我们就通过实例来学习一下Exchanger的用法. Exchanger的简单实例 Exchanger是 ...

  7. java高级---->Thread之FutureTask的使用

    FutureTask类是Future 的一个实现,并实现了Runnable,所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行.今天我们通过实例来学习一下FutureTask的 ...

  8. java高级---->Thread之Condition的使用

    Condition 将 Object 监视器方法(wait.notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set ...

  9. java高级---->Thread之CountDownLatch的使用

    CountDownLatch是JDK 5+里面闭锁的一个实现,允许一个或者多个线程等待某个事件的发生.今天我们通过一些实例来学习一下它的用法. CountDownLatch的简单使用 CountDow ...

随机推荐

  1. efm32 si446x

    Linking target: example-trickle.stk3700arm-none-eabi-gcc -Xlinker -Map=example-trickle.stk3700.map - ...

  2. Quartz 一个JOB 配置多个Trigger时注意的问题

    public class SimpleExample { public void run() throws Exception { Logger log = LoggerFactory.getLogg ...

  3. Win10技巧:如何确定电脑是否适用Hyper-V虚拟机?

    既然微软想要为Hyper-V的普及铺路,那么各种套路……配套措施当然也会一并跟上.比如想要看出电脑是否符合Hyper-V配置要求,有至少两种方式可以参考. 方法一:系统信息 这方法很简单,在Corta ...

  4. Android中使用SoundPool来播放音频

    今天找素材重做FlappyBird时学习了一下怎样为应用设置背景音频,发现通过封装SoundPool类就能够非常好的做到这一点. SoundPool类比較适合播放一些类似游戏音效这样的比較短促并且较小 ...

  5. jsp页面的el表达式取数据

    在jsp页面去Id时候要照上面的方式取,不能照下面的方式取:

  6. 超多的CSS3圆角渐变网页按钮

    <!DOCTYPE html><head><title>超多的CSS3圆角渐变按钮</title><style type="text/c ...

  7. MapReduce初探

    转自 :http://blog.itpub.net/28912557/viewspace-1127423/ Map-Reduce处理过程(分析气象数据的map-reduce过程)1,调用标准的inpu ...

  8. MySQL中乐观锁和悲观锁 原理、区别

    悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁.传统的关系型数据 ...

  9. 【转】PNG图像文件格式

    5.2  PNG图像文件格式 PNG是可携式网络图像(portable network graphics)的英文缩写.PNG是从网络上开始发展的,目的是替代GIF和JPG格式,PNG图像文件格式也是当 ...

  10. 第三百一十八节,Django框架,信号

    第三百一十八节,Django框架,信号 Django中提供了“信号调度”,用于在框架执行操作时解耦.通俗来讲,就是一些动作发生的时候,信号允许特定的发送者去提醒一些接受者. 也就是当程序有指定动作时, ...