class Producter extends Thread
{
CubbyHole cubbyhole;
int productionID = 1;
Producter(CubbyHole c)
{
cubbyhole = c;
}
public void run()
{
for(int i = 0; i < 10; i++)
{
cubbyhole.put(productionID); //生产了一件产品
System.out.println("Product " + productionID++);
try
{
sleep(2000);
}
catch(InterruptedException e)
{
System.out.println("Error: " + e);
}
}
}
}class Customer extends Thread
{
CubbyHole cubbyhole;
int productionID;
Customer(CubbyHole c)
{
cubbyhole = c;
}
public void run()
{
for(int i = 0;i < 10;i++)
{
productionID = cubbyhole.get();
System.out.println("Custom  " + productionID);
}
}
}class CubbyHole
{
int seq;
boolean availlable = false; //初始时文件夹无产品,未满
public synchronized void put(int id)
{
while(availlable == true) //满了
{
try
{
wait(); //等待
}
catch(InterruptedException e)
{
System.out.println("Error: " + e);
}
}
seq = id;
availlable = true; //生产者放入产品,可用了
notify();
}
public synchronized int get()
{
while(availlable == false) //无产品等待
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Error: " + e);
}
}
availlable = false; //消费了产品,文件夹空
notify();
return seq;
}
}
public class ProducterAndCustomer
{
public static void main(String args[])
{
CubbyHole cubbyhole = new CubbyHole();
Producter p = new Producter(cubbyhole);
p.start();
Customer c = new Customer(cubbyhole);
c.start();
}
}
=====================================
输出结果为
Product 1
Custom  1
Custom  2
Product 2
Custom  3
Product 3
Custom  4
Product 4
Product 5
Custom  5
Custom  6
Product 6
Custom  7
Product 7
Custom  8
Product 8
Custom  9
Product 9
Custom  10
Product 10
乱套了,看半天找不出原因,菜鸟请教阿!