首页 > 编程语言 > 详细

java新版中唤醒指定线层对象

时间:2015-08-10 23:36:28      阅读:209      评论:0      收藏:0      [点我收藏+]
import java.util.concurrent.locks.*;    
class Do9 
{
    public static void main(String[] args) 
    {
        Resource r=new Resource();
        Shengchan sc=new Shengchan(r);
        Xiaoshou xs=new Xiaoshou(r);
        Thread th1=new Thread(sc);
        Thread th2=new Thread(sc);
        Thread th3=new Thread(xs);
        Thread th4=new Thread(xs);
        th1.start();
        th2.start();
        th3.start();
        th4.start();
    }
}

class Resource
{
    private String name;
    private int count=1;
    private boolean flag=false;
    //创建一个锁对像
    Lock lock=new ReentrantLock();

    //通过已经有的锁获取该锁上的监视器对象
    Condition shengchan_con=lock.newCondition();//创建生产者对象
    Condition xiaofei_con=lock.newCondition();//创建消费者对象

    public  void set(String name)
    {
        lock.lock();
        try
        {
            while(flag)
                try{shengchan_con.await();}catch(InterruptedException e){}
        this.name=name+count;
        count++;
        System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
        flag=true;
        xiaofei_con.signal();
        }
        finally{
        lock.unlock();
        }
        
            
    }
    public synchronized void out()
    {
        lock.lock();
        try
        {
            while(!flag)
            try{xiaofei_con.await();}catch(InterruptedException e){}
    System.out.println(Thread.currentThread().getName()+"..消费者........"+this.name);
    flag=false;
    shengchan_con.signal();
        }
        finally{
        lock.unlock();
        }
        
    }
}
class Shengchan implements Runnable
{
    private Resource r;

    Shengchan(Resource r)
    {
    this.r=r;
    }
    public void run()
    {
      while(true)
        {
          try{Thread.sleep(150);}catch(InterruptedException e){}
        r.set("烤鸭");
        }
    }

}
class Xiaoshou implements Runnable
{
     private Resource r;
     Xiaoshou(Resource r)
    {
     this.r=r;
     }
    public void run()
    {
    while(true)
        {
        try{Thread.sleep(150);}catch(InterruptedException e){}
        r.out();
        }
    }
}

 

java新版中唤醒指定线层对象

原文:http://www.cnblogs.com/zywf/p/4719310.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!