码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现生产者消费者

时间:2014-09-15 22:55:19      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:java   thread   synchronized   

Java实现生产者消费者
<span style="font-size:18px;">package com.clark.thread;

public class ManTou {
	public int order;
	public ManTou(int order){
		this.order = order;
	}
	
	@Override
	public String toString() {
		return "ManTou:"+this.order;
	}
}
</span>

<span style="font-size:18px;">package com.clark.thread;
//共享栈空间
public class StackBasket {
	public ManTou[] mt = new ManTou[10];
	int index = 0;
	//生产馒头
	public synchronized void push(ManTou m){
		try {
			while(index == mt.length){
				System.out.println("生产满了!!!!!!!");
				this.wait();
			}
			this.notify();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mt[index]=m;
		index++;
		System.out.println("生产了:" + m + " 共" + index + "个馒头");  
	}
	//消费馒头
	public synchronized ManTou pop(){
		try {
			while(index == 0){
				System.out.println("消费完了,请等待!!!!");
				this.wait();
			}
			this.notify();
		} catch (Exception e) {
			
		}
		index--;
		System.out.println("消费了:---------" + mt[index] + " 共" + index + "个馒头"); 
		return mt[index];
	}
}
</span>
<span style="font-size:18px;">package com.clark.thread;
//生产者
public class Producer implements Runnable{
	StackBasket sb = new StackBasket();
	public Producer(StackBasket sb){
		this.sb = sb;
	}
	@Override
	public void run() {
		for (int i = 0; i <8; i++) {
			ManTou m = new ManTou(i);
			sb.push(m);
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
</span>

<span style="font-size:18px;">package com.clark.thread;

public class Consumer implements Runnable{
	StackBasket sb = new StackBasket();
	public Consumer(StackBasket sb){
		this.sb = sb;
	}
	@Override
	public void run() {
		for (int i = 0; i <8; i++) {
			ManTou m = sb.pop();
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
</span>


<span style="font-size:18px;">package com.clark.thread;

public class Test {
	public static void main(String[] args) {
		StackBasket sb = new StackBasket();
		Producer p = new Producer(sb);
		Consumer c = new Consumer(sb);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
	}
}</span>


Java实现生产者消费者

标签:java   thread   synchronized   

原文地址:http://blog.csdn.net/caolipeng_918/article/details/39299235

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!