生产者与消费者模式 (必须将仓库类作为参数传递)

package com.java.basis.threads;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * java多线程模拟生产者消费者问题
    必须将changku作为参数传递,否则无法实现消费
 */
public class ProducerConsumer {
    public static void main(String[] args) {
    	ProducerConsumer p=new ProducerConsumer();
    	 ExecutorService service = Executors.newCachedThreadPool();
    	 changku ck=p.new changku();
    		 shengchan s=p.new shengchan(ck);
    		 xiaofei x=p.new xiaofei(ck);
    		 service.execute(s);
    		 service.execute(x);
    	 service.shutdown();
    }
    
    
    /**
     * 生产
     * @author fliay
     *
     */
    public class shengchan implements Runnable{
    	changku ck=null;
    	public shengchan(changku ck){
    		this.ck=ck;
    	}
    	
		public void run() {
			while(true){
				int name=(int) (Math.random()*1000);
				try {
					Product p=new Product(String.valueOf(name));
					System.out.println("准备生产"+name);
					ck.shengchan(p);
					System.out.println("已经成功生产"+name);
					Thread.sleep(Long.valueOf((long) (Math.random()*2000)));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
    	
    }
    
    /**
     *消费
     * @author fliay
     *
     */
    public class xiaofei implements Runnable{
    	changku ck=null;
    	public xiaofei(changku ck){
    		this.ck=ck;
    	}
    	
		public void run() {
			while(true){
				try{
				int name=(int) (Math.random()*1000);
					Product p=ck.xiaofei();
					System.out.println("用户id:"+name+"已经消费"+p.productName);
					Thread.sleep(Long.valueOf((long) (Math.random()*2000)));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
    	
    }
    /**
     * 仓库类,使用
     * @author fliay
     *
     */
    public class changku{
    	  BlockingQueue<Product> queues = new LinkedBlockingQueue<Product>(10);
    	  
    	  /***
    	   * 生产
    	 * @throws InterruptedException 
    	   */
    	  public void shengchan(Product t) throws InterruptedException{
    		  queues.put(t);
    	  }
    	  
    	  /***
    	   * 消费
    	 * @return 
    	 * @throws InterruptedException 
    	   */
    	  public Product xiaofei() throws InterruptedException{
    		  return queues.take();
    	  }
    	  
    }
    
    
    
    public class Product{
    	private String productName;
    	public Product(String name){
    		this.productName=name;
    	}
    	
    }
}

  

posted @ 2016-10-14 14:57  fliay  阅读(107)  评论(0)    收藏  举报