Java生产者消费者程序模型

生产者消费者模型说明:生产者消费者问题 

Java程序示例如下:

package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AddSub {
	public static void main(String[] args) {
		Goods goods = new Goods();
		
//		Thread t1 = new Thread(new SetTask(goods));
//		Thread t2 = new Thread(new GetTask(goods));
//		
//		t1.start();
//		t2.start();
		
		ExecutorService executor = Executors.newFixedThreadPool(4);
		
		executor.execute(new SetTask(goods));
		executor.execute(new SetTask(goods));
		executor.execute(new GetTask(goods));
		executor.execute(new GetTask(goods));
	}
}

/*
 * 生产者
 */
class SetTask implements Runnable {
	private Goods _goods = null;
	
	public SetTask(Goods goods) {
		_goods = goods;
	}
	
	public void run() {
		while (true) {
			try {
				_goods.set();
				Thread.sleep(1000);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

/*
 * 消费者
 */
class GetTask implements Runnable {
	private Goods _goods = null;
	
	public GetTask(Goods goods) {
		_goods = goods;
	}
	
	public void run() {
		while (true) {
			try {
				_goods.get();
				Thread.sleep(100);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

/*
 * 待生产和消费的物品
 */
class Goods {
	Random _rand = new Random();
	private List<Integer> _list = new ArrayList<Integer>();
	
	Lock _lock = new ReentrantLock();
	Condition _setCondition = _lock.newCondition();
	Condition _getCondition  = _lock.newCondition();
	
	// 生产
	public void set() {
		_lock.lock();
		try {
			while (_list.size() == 5) {
				_setCondition.await();
			}
			int data = _rand.nextInt(10); 
			_list.add(data);
			System.out.println("set() " + data);
			_getCondition.signal();
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		finally {
			_lock.unlock();
		}
	}
	
	// 消费
	public void get() {
		_lock.lock();
		try {
			while (_list.size() == 0) {
				_getCondition.await();
			}
			System.out.println("get() " + _list.remove(0));
			_setCondition.signal();
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		finally {
			_lock.unlock();
		}
	}
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package producer; import java.util.Vector;//输入java矢量 class SyncStack {//实现堆栈功能,不能同时读写 private Vector buffer//私人接口向量缓冲区 = new Vector //新建向量 (400,200); char contents; private boolean ava=false; public synchronized char get() {//出栈 while (ava==false) //如果生产者还没有产生字符就一直等待 { try { this.wait(); } catch (InterruptedException e)//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e. printStackTrace(); } } ava=false; notifyAll(); return contents; } public synchronized void push(char c) { while(ava==true){ try { wait(); } catch (InterruptedException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } }//入栈 ava=true; this.notify();//通知其它线程把数据出栈 Character charObj = new Character(c); buffer.addElement(charObj); contents=c; } public void print(char c) { // TODO 自动生成方法存根 } } class ControlEnter {//每行输出结果的个数 public static int count = 0; void counter() { count++; if(count ==5) { System.out.println(); count = 0; } } } class Producer implements Runnable {//生产者类 private SyncStack theStack;//生产者类获得的字符都来自同步堆栈 private ControlEnter controlenter; public Producer (SyncStack s,ControlEnter ce) { theStack = s; controlenter = ce; } public void run() { char c; for (int i = 0; i < 30; i++) { c = (char)(Math.random() * 26 + 'a');//随机产生30个小写字母 theStack.push(c);//存入堆栈 System.out.print("生产者产生: " + c +" "); controlenter.counter( ); try { Thread.sleep//线程休眠 ((int)(Math.random() * 200));//以0~200ms的速度随机 } catch (InterruptedException e) //当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e.printStackTrace( ); } } } } class Consumer implements Runnable {//消费者类 private SyncStack theStack;//消费者类获得的字符都来自同步堆栈 private ControlEnter controlenter; public Consumer (SyncStack s,ControlEnter ce) { theStack = s; controlenter = ce; } public void run() { char value; for (int i=0; i < 30; i++) {//从堆栈中取数,并输出 value = theStack.get();//取出生产者产生的字母 System.out.print("消费者消费: " + value+" ");//消费者输出 controlenter.counter( ); try { Thread.sleep((int) (Math.random() * 2000));//控制取数的速度:0~2s/*每读取一个字符线程就睡眠*/ } catch (InterruptedException e)//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 { e.printStackTrace(); } } } } public class B {//主线程总调度 public static void main(String []args) { ControlEnter ce = new ControlEnter(); SyncStack stack = new SyncStack();//下面的消费者类对象和生产者类对象所操作的是同一个同步堆栈对象 Producer p1 = new Producer(stack,ce); new Thread(p1).start();//生产者线程启动 Consumer c1 = new Consumer(stack,ce); new Thread(c1).start();//消费者线程启动 } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值