使用线程模拟生产者和消费者示例

package com.work;

/**
 * 测试
 * 
 * @author [email protected]
 * 
 */
public class ProducterConsumerTest {
	public static void main(String[] args) {
		Bag bag = new Bag();
		Producter producter = new Producter(bag);
		Consumer consumer = new Consumer(bag);
		new Thread(producter).start();
		new Thread(consumer).start();
	}
}

/**
 * 汉堡包
 * 
 */
class Hamburger {
	private int id;// 汉堡包生产编号

	public Hamburger(int id) {
		this.id = id;
	}

	public String toString() {
		return " Woto id : " + id;
	}
}

/**
 * 装汉堡包的袋子
 * 
 */
class Bag {
	private static int index = 0;

	private static Hamburger[] wotos = new Hamburger[5];

	/**
	 * 往袋子里面装汉堡包
	 * 
	 * @param woto
	 */
	public synchronized void push(Hamburger woto) {
		while (index == wotos.length) {
			try {
				this.wait();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		wotos[index] = woto;
		index++;
		System.out.println("生产" + woto);
	}

	/**
	 * 从袋子里面拿出汉堡包
	 */
	public synchronized Hamburger pop() {
		while (index == 0) {
			try {
				this.wait();
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		index--;
		System.out.println("消费" + wotos[index]);
		return wotos[index];
	}
}

/**
 * 生产者
 * 
 */
class Producter implements Runnable {

	private Bag bag;

	public Producter(Bag bag) {
		this.bag = bag;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			Hamburger woto = new Hamburger(i);
			bag.push(woto);
		}
	}

}

/**
 * 消费者
 * 
 */
class Consumer implements Runnable {

	private Bag bag;

	public Consumer(Bag bag) {
		this.bag = bag;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			bag.pop();
		}
	}

}

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