package ls0526;
public class Run2
{
// 产品
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<20)
{
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);
Customer customer=new Customer(product);
Thread p1=new Thread(producer,"华为");
Thread p2=new Thread(producer,"联想");
Thread p3=new Thread(producer,"小米");
Thread p4=new Thread(producer,"OPPO");
Thread p5=new Thread(producer,"一加");
Thread p6=new Thread(producer,"魅族");
Thread c1=new Thread(customer,"张三");
Thread c2=new Thread(customer,"李四");
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
c1.start();
c2.start();
}
}
运行结果: