1. 程式人生 > >Condition 與 Object 在通信上的對比

Condition 與 Object 在通信上的對比

== 消費者模式 ble 喚醒 on() @override 多個 ons current

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 \n");;
                    wait();//阻塞線程
                }
                storage.add(new Date());
                System.out.print(Thread.currentThread().getName()+": put:"+storage.size()+ "\n");
                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 \n");;
                    wait();//阻塞線程
                }
                Date d=((LinkedList<Date>)storage).poll();
                System.out.print(Thread.currentThread().getName()+": take:"+storage.size()+ "\n");
                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 \n");;
                notFull.await();//阻塞生產線程
            }
            storage.add(new Date());
            System.out.print(Thread.currentThread().getName()+": put:"+storage.size()+ "\n");
            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 \n");;
                notEmpty.await();//阻塞消費線程
            }
            Date d=((LinkedList<Date>)storage).poll();
            System.out.print(Thread.currentThread().getName()+": take:"+storage.size()+ "\n");
            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();
        }
    }
}

Condition 與 Object 在通信上的對比