Java多線程技術-Lock/Condition,-lockcondition

來源:互聯網
上載者:User

Java多線程技術-Lock/Condition,-lockcondition

在java1.5中Lock對象來實現同步的效果,而且使用上更方便。

使用ReentrantLock實現同步
public class MyService {    private Lock lock = new ReentrantLock();        public void methodA(){        try {            lock.lock();            System.out.println("methodA begin threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());            Thread.sleep(5000);            System.out.println("methodA end threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }        public void methodB(){        try {            lock.lock();            System.out.println("methodB begin threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());            Thread.sleep(5000);            System.out.println("methodB end threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }}public class Test {    public static void main(String[] args) throws InterruptedException {        MyService service = new MyService();        new Thread(()->service.methodA()).start();        new Thread(()->service.methodA()).start();        new Thread(()->service.methodB()).start();        new Thread(()->service.methodB()).start();    }}
View Code

測試結果:調用lock.lock()的線程就持有了“對象監視器”,其他線程只有等待鎖被釋放時再次爭搶,效果和synchronized一樣。

methodA begin threadName=Thread-0 time=1516242293668methodA end threadName=Thread-0 time=1516242298669methodA begin threadName=Thread-1 time=1516242298669methodA end threadName=Thread-1 time=1516242303671methodB begin threadName=Thread-2 time=1516242303671methodB end threadName=Thread-2 time=1516242308672methodB begin threadName=Thread-3 time=1516242308672methodB end threadName=Thread-3 time=1516242313674
使用Condition實現等待/通知
public class MyService {    private Lock lock = new ReentrantLock();    private Condition condition = lock.newCondition();    public void await(){        try {            lock.lock();            System.out.println("await時間為"+System.currentTimeMillis());            condition.await();        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }        public void signal(){        try {            lock.lock();            System.out.println("signal時間為"+System.currentTimeMillis());            condition.signal();        } finally {            lock.unlock();        }    }}public class Run {    public static void main(String[] args) throws InterruptedException {        MyService service = new MyService();        new Thread(()->service.await()).start();        Thread.sleep(3000);        service.signal();    }}
View Code

相似處:

1. 在使用Condition的await方法和signal方法之前比較先調用lock.lock(),否則會拋出異常,跟wait和nofity一樣,需在synchronized的代碼裡運行一樣

2. Object.wait() --> Condition.await(). Object.notify()--> Condition.signal(), Object.notifyAll() -->Condition.signalAll()

優點:

在一個Lock對象裡面可以建立多個Condition執行個體,線程對象可以註冊在指定的Condition中,從而可以有選擇性的進行線程通知,在調度上更加靈活。

使用多個Condition實現通知部分線程
public class MyService {    private Lock lock = new ReentrantLock();    private Condition conditionA = lock.newCondition();    private Condition conditionB = lock.newCondition();    public void awaitA(){        try {            lock.lock();            System.out.println("begin awaitA時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());            conditionA.await();            System.out.println("end awaitA時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }        public void awaitB(){        try {            lock.lock();            System.out.println("begin awaitB時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());            conditionB.await();            System.out.println("end awaitB時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.unlock();        }    }        public void signalAll_A(){        try {            lock.lock();            System.out.println("signalAll_B 時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());            conditionA.signalAll();        } finally {            lock.unlock();        }    }        public void signalAll_B(){        try {            lock.lock();            System.out.println("signalAll_B 時間為"+System.currentTimeMillis() + "Thread name="+Thread.currentThread().getName());            conditionB.signalAll();        } finally {            lock.unlock();        }    }}public class Run {    public static void main(String[] args) throws InterruptedException {        MyService service = new MyService();        new Thread(()->service.awaitA()).start();        new Thread(()->service.awaitB()).start();        Thread.sleep(3000);        service.signalAll_A();    }}
View Code

測試結果:線程B沒有被喚醒

begin awaitA時間為1516244219035Thread name=Thread-0begin awaitB時間為1516244219036Thread name=Thread-1signalAll_B 時間為1516244222035Thread name=mainend awaitA時間為1516244222035Thread name=Thread-0
生產者和消費者
public class MyList {    private Lock lock = new ReentrantLock();    private Condition condition = lock.newCondition();    private volatile List<String> list = new ArrayList<>(10);    public void get() {        try {            System.out.println("get,listSize="+list.size());            lock.lock();            while (list.size() == 0) {                System.out.println("get 等待,ThreadName=" + Thread.currentThread().getName());                condition.await();            }            System.out.println("get -1");            list.remove(0);            condition.signalAll();        } catch (InterruptedException e) {            e.printStackTrace();        } finally{            lock.unlock();        }    }        public void set() {        try {            System.out.println("set,listSize="+list.size());            lock.lock();            while (list.size() == 10) {                System.out.println("set 等待,ThreadName=" + Thread.currentThread().getName());                condition.await();            }            System.out.println("set+1");            list.add("A");            condition.signalAll();        } catch (InterruptedException e) {            e.printStackTrace();        } finally{            lock.unlock();        }    }}public class Run {    public static void main(String[] args) throws InterruptedException {        MyList consumer = new MyList();        for(int i =0;i<10;i++){            new Thread(()->{                while(true){ consumer.set();}            }).start();            new Thread(()->{                while(true){ consumer.get();}            }).start();        }    }}
View CodeReentrantReadWriteLock

ReentrantLock具有完全互斥排他的效果,即在同一時間內只有一個線程在執行ReentrantLock.lock()方法後面的任務。但是效率相對低下,而是用ReentrantReadWriteLock讀寫鎖,可以相對提高效率。讀寫鎖也就是有兩個鎖,一個是和讀相關的鎖,也稱共用鎖定,一個是和寫相關的鎖,也叫排它鎖。只有讀讀鎖之間不互斥,其他都互斥。

讀讀鎖不互斥的例子

public class Service {        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();    public void read(){        try {            lock.readLock().lock();            System.out.println("獲得讀鎖"+Thread.currentThread().getName()+" " + System.currentTimeMillis());            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.readLock().unlock();        }    }}public class Run {    public static void main(String[] args) throws InterruptedException {        Service service = new Service();        new Thread(()->service.read()).start();        new Thread(()->service.read()).start();    }}
View Code

測試結果:幾乎同時獲得讀鎖,說明它們不互斥的

獲得讀鎖Thread-0 1516246020468獲得讀鎖Thread-1 1516246020469

讀寫互斥的例子

public class Service {        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();    public void read(){        try {            lock.readLock().lock();            System.out.println("獲得讀鎖"+Thread.currentThread().getName()+" " + System.currentTimeMillis());            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.readLock().unlock();        }    }        public void write(){        try {            lock.writeLock().lock();            System.out.println("獲得寫鎖"+Thread.currentThread().getName()+" " + System.currentTimeMillis());            Thread.sleep(10000);        } catch (InterruptedException e) {            e.printStackTrace();        } finally {            lock.writeLock().unlock();        }    }}public class Run {    public static void main(String[] args) throws InterruptedException {        Service service = new Service();        new Thread(()->service.read()).start();        new Thread(()->service.write()).start();    }}
View Code

測試結果:寫操作需要等待讀鎖釋放後才能獲得

獲得讀鎖Thread-0 1516246209130獲得寫鎖Thread-1 1516246219132

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.