Java实现生产者消费者

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值