java生产者消费者模式代码示例

package test;

import java.util.LinkedList;

public class Test {
	
	
	public static void main(String[] args) {
		R r = new R();
		P p1 = new P(r,10);
		P p2 = new P(r,20);
		P p3 = new P(r,30);
		P p4 = new P(r,40);
		P p5 = new P(r,50);
		
		C c1 = new C(r,10);
		C c2 = new C(r,20);
		C c3 = new C(r,30);
		C c4 = new C(r,40);
		C c5 = new C(r,50);
		
		new Thread(p1).start();
		new Thread(c1).start();
		

		new Thread(p2).start();
		new Thread(c2).start();
		

		new Thread(p3).start();
		new Thread(c3).start();
		

		new Thread(p4).start();
		new Thread(c4).start();
		

		new Thread(p5).start();
		new Thread(c5).start();
	}
	
	
	
}


class P implements Runnable{
	private R r;
	private int n;
	public P(R _r,int _n){
		this.r = _r;
		this.n = _n;
	}
	@Override
	public void run() {
		r.push(n);
	}
}


class C implements Runnable{
	private R r;
	private int n;
	public C(R _r,int _n){
		this.r = _r;
		this.n = _n;
	}
	@Override
	public void run() {
		r.pop(n);
	}
}



class R {
	private LinkedList<Object> c = new LinkedList<Object>();
	private static final int MAX_SIZE = 100;
	public void push(int n){
		synchronized (c) {
			if(c.size()+n <= MAX_SIZE){
				for(int i=0;i<n;i++){
					c.add(new Object());
				}
				System.out.println("生产者:生产了"+n+"个产品,现在一共有"+c.size()+"个产品,并唤醒消费者线程控可以消费了!!!!!!!");
				c.notifyAll();
			}else{
				System.out.println("生产者:要生产的产品个数:"+n+",大于仓库剩余空间"+(MAX_SIZE-c.size())+"当前生产者线程进入等待状态。。。。。。。。。。");
				try {
					c.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void pop(int n){
		synchronized (c) {
			if(n <= c.size()){
				for(int i=0;i<n;i++){
					c.remove();
				}
				System.out.println("消费者:消费了"+n+"个产品,现在还剩下"+c.size()+"个产品,并唤醒生产者线程控可以生产了!!!!!!!");
				c.notifyAll();
			}else{
				System.out.println("消费者:要消费的产品个数:"+n+",大于仓库剩余产品个数"+c.size()+"当前消费者线程进入等待状态。。。。。。。。。。");
				try {
					c.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

原文地址:https://www.cnblogs.com/iamconan/p/7383528.html