マルチスレッド(一)生産者消費者問題!!!(オリジナル)

3643 ワード

package test;
/**
 * @author  E-mail:[email protected]
 * @version  :2011-11-21  09:14:58
 *  
 */
public class CaoYang {
	static public void main(String[] args){
		
		Loufeng loufeng=new Loufeng(3) ;
		
		new XiaoJie(" ",loufeng,1000).start() ;
		new XiaoJie(" ",loufeng,1000).start() ;
		new XiaoJie(" ",loufeng,1000).start() ;
		new KeRen(" ",loufeng,1000).start() ;
		new KeRen(" ",loufeng,1000).start() ;
		new KeRen(" ",loufeng,1000).start() ;
		
		
		
		
	}

}

 package test;
import java.util.Random;

/**
 * @author E-mail:[email protected]
 * @version  :2011-11-21  09:14:04
 *  
 */
public class KeRen extends Thread{
	
	private final Random random ;
	private final Loufeng loufeng ;
	public KeRen(String name ,Loufeng loufeng,long l){
		super(name) ;
		this.loufeng=loufeng ;
		random=new Random(l) ;
	}
	
	public void run(){
		
		try{
			while(true){
				String cake=loufeng.get() ;
				System.out.println(" :"+cake) ;
				Thread.sleep(random.nextInt(1000)) ;
			}
		}catch(Exception e){
			e.printStackTrace() ;
		}
		
	}
	
	

}

 package test;
/**
 * @author  E-mail:[email protected]
 * @version  :2011-11-21  09:14:42
 *   
 */
public class Loufeng {
	
	
	private int count ;
	private int zou  ;// 
	private  int hui ;// 
	private final String buffer[] ;
	public Loufeng(Integer sum){
		this.buffer=new String[3] ;
		this.count=0 ;
		this.zou=0 ;
		this.hui=0 ;
	}
	
	public synchronized void put(String xiaoj) throws InterruptedException{
		System.out.println(Thread.currentThread().getName()+xiaoj) ;
		while(count>=buffer.length){
			wait() ;
		}
		
		buffer[hui]=xiaoj ;
		hui=(hui+1)%buffer.length ;
		
		count++ ;
		System.out.println(" =============="+count) ;
		this.notifyAll() ;
		
	}
	public synchronized String get() throws InterruptedException{
		while(count<=0){
			wait() ;
		}
		
		String taak=buffer[zou] ;
		zou=(zou+1)%buffer.length ;
		count-- ;
		this.notifyAll() ;
		System.out.println(Thread.currentThread().getName()+" "+taak) ;
		return taak; 
		}
	

}

 package test;
import java.util.Random;

/**
 * @author  E-mail:[email protected]
 * @version  :2011-11-21  09:20:59
 *  
 */
public class XiaoJie extends Thread{
	private final Random random ;
	private final Loufeng  loufeng ;
	private static int i=0 ;
	public XiaoJie(String name ,Loufeng loufeng,long feed){
		super(name) ;
		this.loufeng=loufeng ;
		this.random=new Random(feed) ;
	}
	public void run(){
		
		while(true){
			try {
				Thread.sleep(random.nextInt(1000)) ;
				String cha=" "+getid()+"=== :"+this.getName();
				loufeng.put(cha) ;
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}
	public static final int getid(){
		return i++ ;
	}

}