package buffer;
public class BufferLock //加互斥?的???
{
private int value; //共享?量
private boolean isEmpty = true; //value是否?空的信?量
public synchronized void put(int i) //同步方法
{
while (!isEmpty) //?value不空?,等待
{
try
{
this.wait(); //使?用?方法的?前?程等待,即阻塞自己
}
catch(InterruptedException e) {}
}
value = i; //?value空?,value?得值
isEmpty = false; //?置value?不空??
notify(); //?醒其他等待?程
}
public synchronized int get() //同步方法
{
while (isEmpty) //?value空?,等待
{
try
{
this.wait();
}
catch(InterruptedException e) {}
}
isEmpty = true; //?置value?空??,并返回值
notify();
return value;
}
}
class Pproduced extends Thread //?送?程?
{
private BufferLock buffer;
public Pproduced(BufferLock buffer)
{
this.buffer = buffer;
}
public void run( )
{
for (int i=1;i<20;i++)
{
buffer.put( i );
System.out.println("P produced : " + i );
}
}
}
class Aprocessed extends Thread //接收?程?
{
private BufferLock buffer;
public Aprocessed(BufferLock buffer)
{
this.buffer = buffer ;
}
public void run()
{
for (int i=1; i<20;i++)
System.out.println("\t\t\t A processed : " + buffer.get()) ;
}
public static void main (String args[])
{
BufferLock buffer = new BufferLock();
(new Pproduced(buffer)).start();
(new Aprocessed(buffer)).start();
}
谁知道当Pproduced ,去到 Pproduced 5的时候,可以叫 processed 先消费吗,实际上没看过有生产者生产超过5个以上,消费者还没消费
请问,我要再多加一个消费者,Bprocessed 如何做呢,加了有bug...希望完整解答谢谢.
顺序的消费
P produced : 1
A processed : 1
P produced : 2 B processed 2
P produced : 3 A processed : 3
P produced : 4 B processed 4
繁花如伊
相关分类