java生产者消费者模式代码

package org.hkw.multithread;

public class ThreadDCTest {

	public static void main(String[] args) {
		Thread p = new Thread(new Producer("p1"));
		Thread p2 = new Thread(new Producer("p2"));
		Thread c = new Thread(new Consumer("c1"));
		Thread c2 = new Thread(new Consumer("c2"));
		p.start();
		p2.start();
		c.start();
		c2.start();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Storehouse.getInstance().close();
		p.interrupt();
		p2.interrupt();
		c.interrupt();
		c2.interrupt();

	}

}

class Storehouse {
	static final int STATUS_EMPETY = 0;
	static final int STATUS_FULL = 1;
	boolean isClosed = false;
	String item;
	int status;
	private static Storehouse house = new Storehouse();

	private Storehouse() {
	}

	public static Storehouse getInstance() {
		return house;
	}

	public String getItem() {
		status = STATUS_EMPETY;
		return item;
	}

	public void setItem(String item) {
		status = STATUS_FULL;
		this.item = item;
	}

	public int getStatus() {
		return status;
	}

	public boolean isEmpty() {
		return status == STATUS_EMPETY;
	}

	public boolean isClosed() {
		return isClosed;
	}

	public void close() {
		isClosed = true;
	}
	
	public synchronized void produce(String name) throws InterruptedException
	{
		if (isEmpty()) {
			String item = name + " fill";
			System.out.println(name + " produce item:" + item);
			setItem(item);
			notifyAll();
		} else {
			wait();
		}
	}
	public synchronized void consum(String name) throws InterruptedException{
		if (!isEmpty()) {
			System.out.println(name + " consum item:" + house.getItem());
			notifyAll();
		} else {
			wait();
		}
	}

}

class Producer implements Runnable {
	Storehouse house = Storehouse.getInstance();
	String name;

	public Producer(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println(name + " producer start");
		while (!Thread.currentThread().isInterrupted() && !house.isClosed()) {
			try {
				house.produce(name);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				System.out.println(name + " producer interrupted");
				Thread.currentThread().interrupt();
			}
		}
		System.out.println(name + " producer end");
	}
}

class Consumer implements Runnable {
	Storehouse house = Storehouse.getInstance();
	String name;

	public Consumer(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println(name + " cosumer start");
		while (!Thread.currentThread().isInterrupted() && !house.isClosed()) {
			try {
				house.consum(name);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				System.out.println(name + " cosumer interrupted");
				Thread.currentThread().interrupt();
			}
		}
		System.out.println(name + " consumer end");

	}
}

你可能感兴趣的:(java,thread)