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


    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();
            }
        }
    }
  • 相关阅读:
    【杭电】[4883]TIANKENG’s restaurant
    【杭电】[4883]TIANKENG’s restaurant
    【POJ】[1423]Big Number
    【POJ】[1423]Big Number
    【杭电】[1280]前m大的数
    【杭电】[1280]前m大的数
    【杭电】[1576]A/B
    【杭电】[1576]A/B
    [leetcode]346. Moving Average from Data Stream滑动窗口平均值
    [leetcode]99. Recover Binary Search Tree恢复二叉搜索树
  • 原文地址:https://www.cnblogs.com/zywf/p/4719310.html
Copyright © 2020-2023  润新知