• Condition 与 Object 在通信上的对比


     Condition 将 Object的通信方法(wait、notify 和 notifyAll)分解成截然不同的对象,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),传统线程的通信方式,Condition都可以实现,这里注意,Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法。

    Condition的强大之处在于它可以为多个线程间建立不同的Condition, 使用synchronized/wait()只有一个阻塞队列,notifyAll会唤起所有阻塞队列下的线程,而使用lock/condition,可以实现多个阻塞队列,signalAll只会唤起某个阻塞队列下的阻塞线程。

    - 使用synchronized/wait()实现生产者消费者模式如下:

        //模拟生产和消费的对象
        class Buffer {
            private int maxSize;
            private List<Date> storage;
            Buffer(int size){
                maxSize=size;
                storage=new LinkedList<>();
            }
            //生产方法
            public synchronized void put()  {
                try {
                    while (storage.size() ==maxSize ){//如果队列满了
                        System.out.print(Thread.currentThread().getName()+": wait 
    ");;
                        wait();//阻塞线程
                    }
                    storage.add(new Date());
                    System.out.print(Thread.currentThread().getName()+": put:"+storage.size()+ "
    ");
                    Thread.sleep(1000);
                    notifyAll();//唤起线程
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }       
            }
            //消费方法
            public synchronized void take() {
                try { 
                    while (storage.size() ==0 ){//如果队列满了
                        System.out.print(Thread.currentThread().getName()+": wait 
    ");;
                        wait();//阻塞线程
                    }
                    Date d=((LinkedList<Date>)storage).poll();
                    System.out.print(Thread.currentThread().getName()+": take:"+storage.size()+ "
    ");
                    Thread.sleep(1000);
                    notifyAll();//唤起线程
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }       
            } 
    }
    //生产者
    class Producer implements Runnable{
        private Buffer buffer;
        Producer(Buffer b){
            buffer=b;
        }
        @Override
        public void run() {
            while(true){
                buffer.put();
            }
        }   
    }
    //消费者
    class Consumer implements Runnable{
        private Buffer buffer;
        Consumer(Buffer b){
            buffer=b;
        }
        @Override
        public void run() {
            while(true){
                buffer.take();
            }
        }   
    }
    //
    public class Main{
        public static void main(String[] arg){
            Buffer buffer=new Buffer(10);
            Producer producer=new Producer(buffer);
            Consumer consumer=new Consumer(buffer);
            //创建线程执行生产和消费
            for(int i=0;i<3;i++){
                new Thread(producer,"producer-"+i).start();
            }
            for(int i=0;i<3;i++){
                new Thread(consumer,"consumer-"+i).start();
            }
        }
    }
    

    - 使用lock/condition实现生产者消费者模式如下:

    import java.util.Date;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    
    class Buffer {
        private  final Lock lock;
        private  final Condition notFull;
        private  final Condition notEmpty;
        private int maxSize;
        private List<Date> storage;
        Buffer(int size){
            //使用锁lock,并且创建两个condition,相当于两个阻塞队列
            lock=new ReentrantLock();
            notFull=lock.newCondition();
            notEmpty=lock.newCondition();
            maxSize=size;
            storage=new LinkedList<>();
        }
        public void put()  {
            lock.lock();
            try {   
                while (storage.size() ==maxSize ){//如果队列满了
                    System.out.print(Thread.currentThread().getName()+": wait 
    ");;
                    notFull.await();//阻塞生产线程
                }
                storage.add(new Date());
                System.out.print(Thread.currentThread().getName()+": put:"+storage.size()+ "
    ");
                Thread.sleep(1000);         
                notEmpty.signalAll();//唤醒消费线程
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{   
                lock.unlock();
            }
        }
    
        public  void take() {       
            lock.lock();
            try {  
                while (storage.size() ==0 ){//如果队列满了
                    System.out.print(Thread.currentThread().getName()+": wait 
    ");;
                    notEmpty.await();//阻塞消费线程
                }
                Date d=((LinkedList<Date>)storage).poll();
                System.out.print(Thread.currentThread().getName()+": take:"+storage.size()+ "
    ");
                Thread.sleep(1000);         
                notFull.signalAll();//唤醒生产线程
    
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                lock.unlock();
            }
        } 
    }
    
    class Producer implements Runnable{
        private Buffer buffer;
        Producer(Buffer b){
            buffer=b;
        }
        @Override
        public void run() {
            while(true){
                buffer.put();
            }
        }   
    }
    class Consumer implements Runnable{
        private Buffer buffer;
        Consumer(Buffer b){
            buffer=b;
        }
        @Override
        public void run() {
            while(true){
                buffer.take();
            }
        }   
    }
    public class Main{
        public static void main(String[] arg){
            Buffer buffer=new Buffer(10);
            Producer producer=new Producer(buffer);
            Consumer consumer=new Consumer(buffer);
            for(int i=0;i<3;i++){
                new Thread(producer,"producer-"+i).start();
            }
            for(int i=0;i<3;i++){
                new Thread(consumer,"consumer-"+i).start();
            }
        }
    }
  • 相关阅读:
    电商平台开发笔记5.nuxt项目中深度选择器解决el-input高度设置无效
    电商平台开发笔记4.css选择器之~波浪号使用
    电商平台开发笔记3.nuxt全局css的引入
    电商平台开发笔记2.Nuxt增加对less支持,解决This relative module was not found报错
    电商平台开发笔记1.Nuxt项目创建+Eslint代码保存自动格式化
    vue-cli 4.x 发布前的一些优化
    VueCli 4.x npm run build后主页空白的原因及解决方案
    VSCode 保存时自动ESlint格式化
    git 常用操作笔记
    VSCode下手动构建webpack项目
  • 原文地址:https://www.cnblogs.com/sg9527/p/7753786.html
Copyright © 2020-2023  润新知