多线程生产者和消费者

public class ProductCustomer {
	
	public static void main(String[] args) {
		Storage s = new Storage();
		Producer p = new Producer("生产者p", s);
		Producer d = new Producer("生产者d", s);
		Customer c = new Customer("消费者c", s);
		Customer t = new Customer("消费者t", s);
		new Thread(p).start();
		new Thread(d).start();
		new Thread(c).start();
		new Thread(t).start();
	}
}

public static void main(String[] args) throws InterruptedException {
		Storage s = new Storage();
		Producer p = new Producer("生产者p", s);
		Producer d = new Producer("生产者d", s);
		Customer c = new Customer("消费者c", s);
		Customer t = new Customer("消费者t", s);
		ExecutorService a = Executors.newCachedThreadPool();
		a.submit(p);
		a.submit(d);
		a.submit(c);
		a.submit(t);
	}


public class Customer implements Runnable{
		String name;
		Storage s;
		
		public Customer(String name,Storage s) {
			this.name=name;
			this.s=s;
		}
		
		public void run(){
			try {
			while(true){
				  System.out.println(name + "准备消费产品.");
                  Product product;
				  product = s.getProduct();
                  System.out.println(name + "已消费(" + product.toString() + ").");
                  Thread.sleep(500);
			}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}

public class Producer implements Runnable{
		Storage s =null;
		String name="";
		public Producer(String name,Storage s) {
			this.name =name;
			this.s=s;
		}
		
		public void run(){
			try {
			
			while(true){
				Product product = new Product((int) (Math.random() * 10000)); // 产生0~9999随机整数
                System.out.println(name + "准备生产(" + product.toString() + ").");
				s.storeProduct(product);
                System.out.println(name + "已生产(" + product.toString() + ").");
                Thread.sleep(500);
			}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		
}

public class Storage {
		
		LinkedBlockingQueue<Product> queue = new LinkedBlockingQueue<Product>(10);
		
		//取出产品
		public Product getProduct() throws InterruptedException{
			return queue.take();
		}
		
		//存入产品
		public void storeProduct(Product p) throws InterruptedException{
			queue.put(p);
		}
}

public class Product {
	private int id;
	
	Product(int id){
		this.id=id;
	}
	
	public String  toString(){
	return "产品:"+id;
				
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值