您的位置:首页 > 编程语言 > Java开发

Java基础多线程通讯之生产者消费者模式示例:

2013-01-15 12:07 295 查看
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Product product = new Product();

new Thread(new Producer(product)).start();
new Thread(new Consumer(product)).start();
}
}

class Product
{
private int count;
private boolean flag;

public synchronized void create()
{

while(this.flag)
{
try
{
this.wait();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}

this.count++;
System.out.println(Thread.currentThread().getName()+" create -- :"+this.count);
this.flag = true;
this.notify();

try
{
Thread.sleep(300);
}
catch(Exception e)
{
System.err.println(e.getMessage());
}

}

public synchronized void get()
{
while(!this.flag)
{
try
{
this.wait();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}

System.out.println(Thread.currentThread().getName()+" sale:"+this.count);
this.flag = false;
this.notify();

try
{
Thread.sleep(600);
}
catch(Exception e)
{
System.err.println(e.getMessage());
}

}
}

class Producer implements Runnable
{
private Product product;

public Producer(Product product)
{
this.product = product;
}

public void run()
{
while(true)
{
product.create();
}
}
}

class Consumer implements Runnable
{
private Product product;

public Consumer(Product product)
{
this.product = product;
}

public void run()
{
while(true)
{
product.get();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: