手撕代码(三)Java多线程模拟生产者消费者方法

一时兴起,写个多线程模拟生产者消费者的例子,本来应该更新堆排序的,那就晚上再更吧,最近有点忙呀。下面是我提供的代码,都是手敲的呀,不过没给大家提供导入的包文件,喜欢的朋友,复制黏贴过去然后编译器自然会导入的。最近好忙,看不到目标,继续往前好了

思路:搞清楚一下这几点就OK    

仓库类:提供一个数据结构存储产品,两个方法,一个生产者调用生产,一个消费者调用消费    

产品类:提供产品的id和toStrng()方法的重写 

生产者类:实现多线程调度,实现构造器方法和run()方法的重写 

消费者类:实现多线程调度,实现构造器方法和run()方法的重写.

public class SXThread{
	public static void main(String[] args){
		SXThread sx = new SXThread();
		//仓库类
		Storage s  = sx.new Storage();
		//生产者
		Producer p1 = sx.new Producer("生产者一",s);
		Producer p2 = sx.new Producer("生产者二",s);
		//消费者
		Customer c1 = sx.new Customer("消费者一",s);
		Customer c2 = sx.new Customer("消费者二",s);
		Customer c3 = sx.new Customer("消费者三",s);
		//线程池
		ExecutorService service = Executors.newCachedThreadPool();
		//线程启动
		service.submit(p1);
		service.submit(p2);
		service.submit(c1);
		service.submit(c2);
		service.submit(c3);
	}
	//仓库类,存储生产者生产的和消费者消费的产品提供存取两个方法
	 class Storage{
		BlockingQueue queue = new LinkedBlockingQueue();
		public void push(Product p) throws InterruptedException{
			queue.put(p);
		}
		public Product pop() throws InterruptedException{
			return queue.take();
		}
	}
	//产品类只提供产品id,重写了toString()方法
	class Product{
		private int id;
		public Product(int id){
			this.id = id;
		}
		public String toString(){
			return "产品"+this.id+"号";
		}
	}
	//生产者实现多线程
	class Producer implements Runnable{
		private String name;
		private Storage s;
		public Producer(String name,Storage s){
			this.name = name;
			this.s = s;
		}
		//先生产出产品再入库
		public void run(){
			
			try {
				while(true){
					Product p = new Product((int)(Math.random()*1000));
					s.push(p);
					System.out.println(name+"生产了"+p.toString());
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
		//TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//消费者实现多线程
	class Customer implements Runnable{
		private String name;
		private Storage s;
		public Customer(String name,Storage s){
			this.name = name;
			this.s = s;
		}
		//出库消费
		public void run(){
			
			try {
				while(true){
					Product p = s.pop();
					System.out.println(name+"消费了"+p.toString());
					Thread.sleep(500);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

手撕代码(三)Java多线程模拟生产者消费者方法_第1张图片

你可能感兴趣的:(Java&笔试)