专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 人工智能

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

发布时间:2011-07-03 07:44:16 文章来源:www.iduyao.cn 采编人员:星星草
<script language="javascript"> c_a_3(); </script>
wait和notify实现的生产者消费者线程交互


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();
}
}
}
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: