天天看点

Java 生产者消费者模式示例

package test;

public class 生产者消费者示例 {
	public static void main(String[] args) {
		Res r = new Res("面包");
		Productor p = new Productor(r);
		Customer c = new Customer(r);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
		
		Productor p2 = new Productor(r);
		Customer c2 = new Customer(r);
		Thread t3 = new Thread(p2);
		Thread t4 = new Thread(c2);
		t3.start();
		t4.start();
	}
}

class Productor implements Runnable{
	private Res r;
	Productor(Res r){
		this.r = r;
	}
	
	public void run(){
		try {
			r.set();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Customer implements Runnable{
	private Res r;
	Customer(Res r){
		this.r = r;
	}
	
	public void run(){
		try {
			r.out();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class Res{
	private String name;
	private int count = 1;
	private boolean f = false;
	
	Res(String name){
		this.name = name;
	}
	
	public synchronized void set() throws InterruptedException{
		while(true){
			while(f)
				wait();
			count ++;
			System.out.println("生产 --- " + this.name + count);
			f = true;
			notifyAll();
		}
	}
	
	public synchronized void out() throws InterruptedException{
		while(true){
			while(!f)
				wait();
			System.out.println("消费 ---------------" + name);
			f = false;
			notifyAll();
		}
	}
}