您的位置:首页 > 产品设计 > UI/UE

Java使用阻塞队列BlockingQueue实现线程同步

2015-09-09 16:16 696 查看
一、BlockingQueue简介

BlockingQueue是java.util.concurrent包提供的一个接口,经常被用于多线程编程中容纳任务队列。它提供了两个支持阻塞的方法:

put(E e):尝试把元素e放入队列中,如果队列已满,则阻塞当前线程,直到队列有空位。

take():尝试从队列中取元素,如果没有元素,则阻塞当前线程,直到取到元素。

BlockingQueue有很多实现类,如ArrayBlockingQueue,LinkedBlockingQueue,PriorityBlockingQueue等等。

二、使用场景

目前理解BlockingQueue比较适合生产者——消费者者模式的多线程并发场景,多个线程产生任务,多个线程完成任务。下面用一个卖煎饼和买煎饼的示例介绍BlockingQueue的简单用法。

package com;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
* 本例演示了使用BlockingQueue来实现生产者消费者模式<商家做煎饼、和买煎饼>
*/
public class Main {

public static void main(String[] args) throws Exception {
// 架设商家的煎饼摊子上只能摆4个煎饼
final BlockingQueue<String> m = new ArrayBlockingQueue<>(4);

// 开启线程——模拟商家不停做煎饼
new Thread(new Runnable() {
@Override
public void run() {
int count = 1;// 生产的煎饼总数
while (true) {
try {
m.put("煎饼" + count);
System.out.println("做好了煎饼" + count);
count++;
Thread.sleep(4000); //休息4S
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

// 不停的创建买家来买煎饼
while (true) {
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread()+"来买煎饼了");
System.out.println(Thread.currentThread()+"买到了" + m.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(2000);
}
}
}


三、结果演示

做好了煎饼1
Thread[Thread-1,5,main]来买煎饼了
Thread[Thread-1,5,main]买到了煎饼1
Thread[Thread-2,5,main]来买煎饼了
做好了煎饼2
Thread[Thread-2,5,main]买到了煎饼2
Thread[Thread-3,5,main]来买煎饼了
Thread[Thread-4,5,main]来买煎饼了
做好了煎饼3
Thread[Thread-3,5,main]买到了煎饼3
Thread[Thread-5,5,main]来买煎饼了
Thread[Thread-6,5,main]来买煎饼了
做好了煎饼4
Thread[Thread-4,5,main]买到了煎饼4
Thread[Thread-7,5,main]来买煎饼了
Thread[Thread-8,5,main]来买煎饼了
做好了煎饼5
Thread[Thread-5,5,main]买到了煎饼5
Thread[Thread-9,5,main]来买煎饼了
Thread[Thread-10,5,main]来买煎饼了
做好了煎饼6
Thread[Thread-6,5,main]买到了煎饼6
Thread[Thread-11,5,main]来买煎饼了
Thread[Thread-12,5,main]来买煎饼了
做好了煎饼7
Thread[Thread-7,5,main]买到了煎饼7
Thread[Thread-13,5,main]来买煎饼了
Thread[Thread-14,5,main]来买煎饼了
做好了煎饼8
Thread[Thread-8,5,main]买到了煎饼8
Thread[Thread-15,5,main]来买煎饼了
Thread[Thread-16,5,main]来买煎饼了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: