生产者消费者java算法解释_经典算法:生产者与消费者(JAVA实现)

该程序可以直接运行,希望对大家了解java线程和生产者与消费者算法有所帮助。

public class ProducterAndConsumer

{

//也可以定义多个生产者和消费者

//但得用notifyAll()

public static void main(String[] args)

{

SynStack ss = new SynStack();

Producter pro = new Producter(ss);

Thread proth = new Thread(pro);

Consumer con = new Consumer(ss);

Thread conth = new Thread(con);

proth.start();

conth.start();

}

}

//定义一个面包对象

class Bread

{

private int id = 0;

public int getId()

{

return id;

}

Bread(){}

Bread(int id)

{

this.id = id;

}

}

//定义一个栈用来放面包

class SynStack

{

private static int nowIndex = -1;

public static final int MAXLENGTH = 10;

private static Bread[] breads = new Bread[MAXLENGTH];

public synchronized void push(Bread bread)

{

//在这里不能用if,因为可能会捕获InterruptedException异常,如果用if的话执行完

//e.printStackTrace()后会直接执行this.notify();breads[nowIndex] = bread;nowIndex++;

//但是应该继续判断,所以得用while

while(nowIndex > (MAXLENGTH - 2))

{

try

{

this.wait();

}

catch(InterruptedException e)

{

e.printStackTrace();

}

}

this.notify();

nowIndex++;

breads[nowIndex] = bread;

}

public synchronized Bread take()

{

while(nowIndex < 0)

{

try

{

this.wait();

}

catch(InterruptedException e)

{

e.printStackTrace();

}

}

this.notify();

Bread bread = breads[nowIndex];

nowIndex--;

return bread;

}

public static int getNowIndex() {

return nowIndex;

}

public static void setNowIndex(int nowIndex) {

SynStack.nowIndex = nowIndex;

}

}

class Producter implements Runnable

{

private SynStack ss = null;

private int time = 0;

public Producter(SynStack ss)

{

this.ss = ss;

}

public void run()

{

synchronized (ss)

{

while (true)

{

Bread bread = new Bread(time);

ss.push(bread);

System.out.println("生产了面包" + time + "放在篮子的" + ss.getNowIndex());

time++;

}

}

}

}

class Consumer implements Runnable

{

private SynStack ss = null;

public Consumer(SynStack ss)

{

this.ss = ss;

}

public void run()

{

synchronized (ss)

{

while (true)

{

Bread bread = ss.take();

System.out.println("消费了面包" + bread.getId() + "放在篮子的"

+ (ss.getNowIndex() + 1));

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值