zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    【WPF学习】第六十二章 构建更复杂的模板
    【WPF学习】第六十一章 组织模板资源
    【WPF学习】第六十章 创建控件模板
    【WPF学习】第五十九章 理解控件模板
    Fast-Rcnn论文翻译
    在pytorch下使用tensorboardX(win10;谷歌浏览器;jupyter notebook)
    win10下cuda安装以及利用anaconda安装pytorch-gpu过程
    JS this的指向
    JS promise对象
    JS 正则表达式
  • 原文地址:https://www.cnblogs.com/zywf/p/4719310.html
Copyright © 2011-2022 走看看