`
xly_971223
  • 浏览: 1266211 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

多线程之Producer-Consumer Pattern

    博客分类:
  • java
 
阅读更多
生产者/消费者模式
有两个厨师在做蛋糕(生产者)两个客人在吃蛋糕(消费者)
厨师做好了就放在桌子上,客人吃完了就从桌子上取,桌子实际上是共享队列
桌子最多能放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();
		}
		
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics