package ls0526;
public class Run
{
// 产品
public static class Product
{
public int count=0;
}
// 生产者
public static class Producer implements Runnable
{
private Product product;
public Producer(Product product)
{
super();
this.product = product;
}
public void run()
{
while(true)
{
synchronized (product)
{
if(product.count==0)
{
product.count++;
System.out.println(Thread.currentThread().getName()+"生产了"+product.count);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
// 消费者
public static class Customer implements Runnable
{
private Product product;
public Customer(Product product)
{
super();
this.product = product;
}
public void run()
{
while(true)
{
synchronized (product)
{
if(product.count>0)
{
System.out.println(Thread.currentThread().getName()+"消费了"+product.count);
product.count--;
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args)
{
Product product=new Product();
Producer producer=new Producer(product);
Thread t1=new Thread(producer);
Thread t2=new Thread(producer);
Customer customer=new Customer(product);
Thread t3=new Thread(customer);
Thread t4=new Thread(customer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
运行结果: