java多线程队列_java多线程消费者生产者模式(BlockingQueue 通过阻塞队列实现)
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created with IntelliJ IDEA.
* User: csx
* Date: 4/24/14
* Time: 9:56 AM
* To change this template use File | Settings | File Templates.
*
* 生產(chǎn)者與消費(fèi)者模型中,要保證以下幾點(diǎn):
* 1 同一時(shí)間內(nèi)只能有一個(gè)生產(chǎn)者生產(chǎn)
* 2 同一時(shí)間內(nèi)只能有一個(gè)消費(fèi)者消費(fèi)
* 3 生產(chǎn)者生產(chǎn)的同時(shí)消費(fèi)者不能消費(fèi)
* 4 消費(fèi)者消費(fèi)的同時(shí)生產(chǎn)者不能生產(chǎn)
* 5 共享空間空時(shí)消費(fèi)者不能繼續(xù)消費(fèi)
* 6 共享空間滿時(shí)生產(chǎn)者不能繼續(xù)生產(chǎn)
*
* 使用并發(fā)庫(kù)中的BlockingQueue(阻塞隊(duì)列) 實(shí)現(xiàn)生產(chǎn)者與消費(fèi)者
*/
public class WaitNoticeDemo {
public static void main(String[] args) {
//固定容器大小為10
BlockingQueue foods = new LinkedBlockingQueue(10);
Thread produce = new Thread(new Produce(foods));
Thread consume = new Thread(new Consume(foods));
produce.start();
consume.start();
}
}
/**
* 生產(chǎn)者
*/
class Produce implements Runnable{
private BlockingQueue foods;
Produce(BlockingQueue foods) {
this.foods = foods;
}
@Override
public void run() {
int i = 0;
while (true){
try {
//當(dāng)生產(chǎn)的食品數(shù)量裝滿了容器,那么在while里面該食品容器(阻塞隊(duì)列)會(huì)自動(dòng)阻塞 ?wait狀態(tài) 等待消費(fèi)
foods.put(new Food("食品"+i));
i++;
} catch (InterruptedException e) {
e.printStackTrace(); ?//To change body of catch statement use File | Settings | File Templates.
}
}
}
}
/**
* 消費(fèi)者
*/
class Consume implements Runnable {
private BlockingQueue foods;
Consume(BlockingQueue foods){
this.foods = foods;
}
@Override
public void run() {
try {
Thread.sleep(1000); ?//用于測(cè)試當(dāng)生產(chǎn)者生產(chǎn)滿10個(gè)食品后是否進(jìn)入等待狀態(tài)
while (true){
//當(dāng)容器里面的食品數(shù)量為空時(shí),那么在while里面該食品容器(阻塞隊(duì)列)會(huì)自動(dòng)阻塞 ?wait狀態(tài) 等待生產(chǎn)
Food food = foods.take();
System.out.println("消費(fèi)"+food.getName());
}
} catch (InterruptedException e) {
e.printStackTrace(); ?//To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* 食品
*/
class Food{
private String name;
String getName() {
return name;
}
Food(String name){
this.name = name;
System.out.println("生產(chǎn)"+name);
}
}
如有不足 還請(qǐng)大家留言糾正修改。
總結(jié)
以上是生活随笔為你收集整理的java多线程队列_java多线程消费者生产者模式(BlockingQueue 通过阻塞队列实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: win7系统怎么看显卡 Win7如何查看
- 下一篇: es集群搭建_滴滴Elasticsear