多线程之Producer-Consumer Pattern

生产者/消费者模式
有两个厨师在做蛋糕(生产者)两个客人在吃蛋糕(消费者)
厨师做好了就放在桌子上,客人吃完了就从桌子上取,桌子实际上是共享队列
桌子最多能放3个蛋糕,放满了后厨师就等待 直到客人取走一个
整理后包括着几个类
MakerThread 厨师
EaterThread 客人
Table 共享队列
还有就是蛋糕了 我们用String来表示

package com.justel.fs.prod_cons;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 生产者
* @author 徐良永
* @date 2013-6-7下午1:17:06
*/
public class MakerThread extends Thread{
private static AtomicInteger i = new AtomicInteger(0);
private Table table;
private Random random = new Random();
public MakerThread(Table table, String name){
super(name);
this.table = table;
}

public void run(){
try {
while(true){
String cake = "蛋糕"+i.getAndIncrement();
table.put(cake);
System.out.println(Thread.currentThread().getName() + "正在做:" + cake);
Thread.sleep(random.nextInt(500));
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

package com.justel.fs.prod_cons;

import java.util.Random;

/**
* 消费者
* @author 徐良永
* @date 2013-6-7下午1:17:36
*/
public class EaterThread extends Thread{
private Table table;
Random random = new Random();

public EaterThread(Table table, String name){
super(name);
this.table = table;
}

public void run(){
try {
while (true) {
String cake = table.get();
System.out.println(Thread.currentThread().getName() + "正在吃:" + cake);
//random.nextInt(10000);1000
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

/**
* 共享队列
* @author 徐良永
* @date 2013-6-7下午1:18:10
*/
public class Table {

private LinkedList<String> linkedList = new LinkedList<>();

public synchronized String get() throws InterruptedException{
while (linkedList.isEmpty()) {
wait(); //队列空了 所有消费线程转入等待状态
}

String s = linkedList.removeFirst();
notifyAll(); //通知所有生产线程---队列有空位了
return s;
}

public synchronized void put(String s)throws InterruptedException{
while(linkedList.size() >= 3){
System.out.println("-----------桌子已经放满了------------");
wait(); //队列满了 生产线程转为等待状态
}

linkedList.add(s);
notifyAll(); //通知所有消费线程---队列有数据了
}
}


public class Main {

public static void main(String[] args) {
Table table = new Table();

for (int i = 0; i < 3; i++) {
new EaterThread(table, "吃货" + i).start();
new MakerThread(table, "厨师" + i).start();
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值