Java多線程——Lock&Condition

來源:互聯網
上載者:User

標籤:private   rac   nbsp   nal   dom   strong   zha   技術   允許   

Lock比傳統執行緒模式中的synchronized方式更加物件導向,與生活中的鎖類似,鎖本身也應該是一個對象。兩個線程執行的程式碼片段要實現同步互斥的效果,它們必須用同一個Lock對象。

package java_thread;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class LockTest {/** * @param args */public static void main(String[] args) {new LockTest().init();}private void init(){final Outputer outputer = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {while(true){try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output("zhangxiaoxiang");}}}).start();new Thread(new Runnable(){@Overridepublic void run() {while(true){try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}outputer.output("lihuoming");}}}).start();}static class Outputer{Lock lock = new ReentrantLock();public void output(String name){int len = name.length();lock.lock();try{for(int i=0;i<len;i++){System.out.print(name.charAt(i));}System.out.println();}finally{lock.unlock();}}public synchronized void output2(String name){int len = name.length();for(int i=0;i<len;i++){System.out.print(name.charAt(i));}System.out.println();}public static synchronized void output3(String name){int len = name.length();for(int i=0;i<len;i++){System.out.print(name.charAt(i));}System.out.println();}}}

 

讀寫鎖:分為讀鎖和寫鎖,多個讀鎖不互斥,讀鎖與寫鎖互斥,這是由jvm自己控制的,你只要上好相應的鎖即可。如果你的代碼唯讀資料,可以很多人同時讀,但不能同時寫,那就上讀鎖;如果你的代碼修改資料,只能有一個人在寫,且不能同時讀取,那就上寫鎖。總之,讀的時候上讀鎖,寫的時候上寫鎖!

package java_thread;import java.util.Random;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class ReadWriteLockTest {public static void main(String[] args) {final Queue3 q3 = new Queue3();for(int i=0;i<3;i++){new Thread(){public void run(){while(true){q3.get();}}}.start();new Thread(){public void run(){while(true){q3.put(new Random().nextInt(10000));}}}.start();}}}class Queue3{private Object data = null;//共用資料,只能有一個線程能寫該資料,但可以有多個線程同時讀該資料。ReadWriteLock rwl = new ReentrantReadWriteLock();public void get(){rwl.readLock().lock();try {System.out.println(Thread.currentThread().getName() + " be ready to read data!");Thread.sleep((long)(Math.random()*1000));System.out.println(Thread.currentThread().getName() + "have read data :" + data);} catch (InterruptedException e) {e.printStackTrace();}finally{rwl.readLock().unlock();}}public void put(Object data){rwl.writeLock().lock();try {System.out.println(Thread.currentThread().getName() + " be ready to write data!");Thread.sleep((long)(Math.random()*1000));this.data = data;System.out.println(Thread.currentThread().getName() + " have write data: " + data);} catch (InterruptedException e) {e.printStackTrace();}finally{rwl.writeLock().unlock();}}}

 讀的時候可以被讀打斷,寫的時候不能太打斷

 

在等待 Condition 時,允許發生“虛假喚醒”,這通常作為對基礎平台語義的讓步。對於大多數應用程式,這帶來的實際影響很小,因為 Condition 應該總是在一個迴圈中被等待,並測試正被等待的狀態聲明。某個實現可以隨意移除可能的虛假喚醒,但建議應用程式程式員總是假定這些虛假喚醒可能發生,因此總是在一個迴圈中等待。

一個鎖內部可以有多個Condition,即有多路等待和通知,可以參看jdk1.5提供的Lock與Condition實現的可阻塞隊列的應用案例,從中除了要體味演算法,還要體味物件導向的封裝。在傳統的線程機制中一個監視器對象上只能有一路等待和通知,要想實現多路等待和通知,必須嵌套使用多個同步監視器對象。(如果只用一個Condition,兩個放的都在等,一旦一個放的進去了,那麼它通知可能會導致另一個放接著往下走。)

Java多線程——Lock&Condition

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.