`
sgl124764903
  • 浏览: 170440 次
  • 性别: Icon_minigender_1
  • 来自: 邯郸
社区版块
存档分类
最新评论

生产者消费者问题

    博客分类:
  • J2SE
阅读更多
public class TextThread {
	public static void main(String[] args) {
		Basket bk = new Basket();
		Producer p = new Producer(bk);
		Consumer c = new Consumer(bk);

		new Thread(p).start();
		new Thread(c).start();
	}
}

class ManTou {
	int id;

	ManTou(int id) {
		this.id = id;
	}

	public String toString() {
		return  id+"号馒头";
	}
}

class Basket {
	static int index = 0;
	ManTou[] mArray = new ManTou[6];

	public synchronized void add(ManTou m) {
		while (index == mArray.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		
		mArray[index] = m;
		index++;

	}

	public synchronized ManTou del() {
		while (index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notify();
		index--;
		return mArray[index];

	}
}

class Producer implements Runnable {
	Basket bk = null;

	Producer(Basket bk) {
		this.bk = bk;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			ManTou mt = new ManTou(i);
			bk.add(mt);
			System.out.println("生产了" + mt);
//			try {
//				Thread.sleep(500);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
		}
	}
}

class Consumer implements Runnable {
	Basket bk = null;

	Consumer(Basket bk) {
		this.bk = bk;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			ManTou mt = bk.del();
			System.out.println("消费了" + mt);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

生产了0号馒头
生产了1号馒头
生产了2号馒头
生产了3号馒头
生产了4号馒头
生产了5号馒头
生产了6号馒头
消费了5号馒头
消费了6号馒头
生产了7号馒头
消费了7号馒头
生产了8号馒头
消费了8号馒头
生产了9号馒头
消费了9号馒头
消费了4号馒头
消费了3号馒头
消费了2号馒头
消费了1号馒头
消费了0号馒头

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics