码迷,mamicode.com
首页 > 编程语言 > 详细

wait和notify实现的生产者消费者线程交互

时间:2014-07-01 07:02:56      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:多线程   thread   生产者消费者 wait notifyal   



public class ProductTest {
public static void main(String args[])
{
Repertory repertory=new Repertory();
new Thread(new Producer(repertory)).start();
new Thread(new Consumer(repertory)).start();
}
}


class Repertory{
private int product=0;

public synchronized void addProduct(){
if(this.product>=5)
{
try{
this.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}
else
{
product++;
System.out.println("生产者生成第"+product+"个产品");
this.notifyAll();
}
}

public synchronized void getProduct(){
if(this.product<=0)
{
try{
this.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}else
{
System.out.println("消费者取走了第"+product+"个产品");
product--;
this.notifyAll();
}
}

}


class Producer implements Runnable{
private Repertory repertory;
public Producer(Repertory repertory){
this.repertory=repertory;
}

public void run(){
System.out.println("生产者开始生产产品");
while(true){
try{
Thread.sleep((int)(Math.random()*10)*100);
}catch(Exception e)
{
e.printStackTrace();
}
repertory.addProduct();
}
}
}




class Consumer implements Runnable{
private Repertory repertory;
public Consumer(Repertory repertory){
this.repertory=repertory;
}

public void run(){
System.out.println("消费者开始取走产品");
while(true)
{
try{
Thread.sleep((int)(Math.random()*10)*100);
}catch(Exception e)
{
e.printStackTrace();
}
repertory.getProduct();
}
}
}

wait和notify实现的生产者消费者线程交互,布布扣,bubuko.com

wait和notify实现的生产者消费者线程交互

标签:多线程   thread   生产者消费者 wait notifyal   

原文地址:http://blog.csdn.net/u014199750/article/details/35988109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!