经典算法:生产者与消费者(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));
}
}
}
}


你可能感兴趣的:(操作系统)