当前位置: 代码迷 >> Web前端 >> 生产者和消费者有关问题
  详细解决方案

生产者和消费者有关问题

热度:404   发布时间:2012-09-09 09:27:54.0
生产者和消费者问题
感觉还有点小问题 , 大家帮忙看看


import java.util.ArrayList;

public class Generant_Customer {
	public static void main(String[] args) {
		Collection c = new Collection();
		Generant gen = new Generant(c);
		Customer cus = new Customer(c);
	
		new Thread(gen,"gen01").start();
		new Thread(gen,"gen02").start();
		new Thread(gen,"gen03").start();
		new Thread(cus,"cus01").start();
		new Thread(cus,"cus02").start();
	}
}
/**
 * 资源类 , 消费者和生产者共同操作的资源
 */
class Collection {
	ArrayList<String> collection = new ArrayList<String>();
	static final int length = 10;
	int index = 1 ;
	int operateCount = 0;
	
	/* 生产者生产 */
	public synchronized void add(){
		if(collection.size()>=length){
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("add() has been interrupted !");
				System.exit(1);
			}
		}
		notifyAll();//唤醒在此对象监视器上等待的单个线程  
		collection.add("馒头  编号:"+index);
		System.out.println("生产者" +Thread.currentThread().getName() + collection.get(index-1));
		index ++ ;
		operateCount++;
	}
	
	/* 消费者消费 */
	public synchronized void pop(){
		if(collection.size() == 0){
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("pop() has been interrupted !");
				System.exit(1);
			}
		}
		notifyAll(); //唤醒在此对象监视器上等待的单个线程   
		System.out.println("--消费者" +Thread.currentThread().getName() + collection.get(collection.size()-1));
		collection.remove(collection.size()-1);
		index -- ;
		operateCount++;
	}
}

class Generant implements Runnable{
	Collection coll = null ;
	
	public Generant(Collection collection ){
		this.coll = collection ;
	}
	
	/* 生产者开始执行 */
	public void run() {
		while(true){
			coll.add();
			System.out.println(coll.operateCount);
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				System.out.println("Generant.run() has been interrupted !\\n" +
						" System continue...");
			}
		}
	}
}

class Customer implements Runnable{
	Collection coll = null ;
	/* 线程开关 */
	boolean doRun = true ;
	
	public Customer(Collection collection ){
		this.coll = collection ;
	}
	/* 消费者开始执行 */
	public void run() {
		while(doRun){
			coll.pop();
			System.out.println(coll.operateCount);
			try {
				Thread.sleep(150);
			} catch (InterruptedException e) {
				System.out.println("Customer.run() has been interrupted !\\n" +
				" System continue...");
			}
			if(coll.operateCount == 50){
				doRun = false;
			}
		}
	}
	
}


  相关解决方案