Java多線程之死結與線程間通訊簡單案例

來源:互聯網
上載者:User

標籤:rup   rod   produce   sum   ber   嵌套   nts   通訊   產生   

死結定義
死結是指兩個或者多個線程被永久阻塞的一種局面,產生的前提是要有兩個或兩個以上的線程,並且來操作兩個或者多個以上的共同資源;我的理解是用兩個線程來舉例,現有線程A和B同時操作兩個共同資源a和b,A操作a的時候上鎖LockA,繼續執行的時候,A還需要LockB進行下面的操作,這個時候b資源在被B線程操作,剛好被上了鎖LockB,假如此時線程B剛好釋放了LockB則沒有問題,但沒有釋放LockB鎖的時候,線程A和B形成了對LockB鎖資源的爭奪,從而造成阻塞,形成死結;具體其死結代碼如下:

public class MyDeadLockTest {    public static void main(String[] args){        Object obj1 = new Object();        Thread thread1 = new Thread(new DeadRes(true,obj1));        Thread thread2 = new Thread(new DeadRes(false,obj1));        thread1.start();        thread2.start();    }}class DeadRes implements Runnable{    boolean flag;    Object obj;    public DeadRes(boolean flag, Object obj1) {        this.flag = flag;        this.obj = obj1;    }    @Override    public void run() {            if(flag){                synchronized (DeadRes.class){                    System.out.println(Thread.currentThread().getName()+" acquie lock is DeadRes.class");                    synchronized (obj){                        System.out.println(Thread.currentThread().getName()+" acquie lock is obj");                    }                }            }else{                synchronized (obj){                    System.out.println(Thread.currentThread().getName()+" acquie lock is obj");                    synchronized (DeadRes.class){                        System.out.println(Thread.currentThread().getName()+" acquie lock is DeadRes.class");                    }                }            }    }}

執行結果如:

Thread-1 acquie lock is objThread-0 acquie lock is DeadRes.class

當然每次執行的結果不一樣,有可能是一種和諧狀態,沒有發生死結,此時為保證每次死結,可以讓run()方法中,執行while(true)迴圈,這樣保證了每次必定發生死結;當然實際應用中,我們應該盡量避免死結,當有多線程操作多個共同資源的時候,避免發生同一鎖對象的同步嵌套。

線程間的通訊—-生產者與消費者模式
1、讓兩個線程交替進行操作,當生產了一個數字後,緊接著消費一個,首先採用Object對象中的wait-notify來實現,具體代碼如下:

public class ThreadProConsume {    public static void main(String[] args){        Product  product = new Product();        Thread thread1 = new Thread(new Producer(product));        Thread thread2 = new Thread(new Consumer(product));        thread1.start();        thread2.start();    }}class Product{    String name;    private int count = 1;    boolean flag = false;    public synchronized void set(String name){        if(flag){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.name = name +"--"+count++;        flag = true;        System.out.println(Thread.currentThread().getName()+" produce num  : "+this.name);        this.notify();    }    public synchronized void out(){        if(!flag){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName()+" consume num  is   : "+this.name);        flag = false;        this.notify();    }}class Producer implements Runnable{    Product res;    public Producer(Product product) {        this.res = product;    }    @Override    public void run() {        while(true){            res.set("guyue");        }    }}class Consumer implements Runnable{    Product res;    public Consumer(Product product) {        this.res = product;    }    @Override    public void run() {        while(true){            res.out();        }    }}

執行結果

Thread-1 consume num  is   : guyue--3938Thread-0 produce num  : guyue--3939Thread-1 consume num  is   : guyue--3939Thread-0 produce num  : guyue--3940Thread-1 consume num  is   : guyue--3940Thread-0 produce num  : guyue--3941Thread-1 consume num  is   : guyue--3941

當超過兩個以上線程操作的時候,這裡需要在set()與out()方法中的if判斷改為while,並且notif方法,改為notifyAll(),這樣多個線程操作的時候,便可以交替進行,具體代碼如下:

public class ThreadProConsume {    public static void main(String[] args){        Product  product = new Product();        Thread thread1 = new Thread(new Producer(product));        Thread thread3 = new Thread(new Producer(product));        Thread thread2 = new Thread(new Consumer(product));        Thread thread4 = new Thread(new Consumer(product));        thread1.start();        thread3.start();        thread2.start();        thread4.start();    }}class Product{    String name;    private int count = 1;    boolean flag = false;    public synchronized void set(String name){        while(flag){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.name = name +"--"+count++;        flag = true;        System.out.println(Thread.currentThread().getName()+" produce num  : "+this.name);        this.notifyAll();    }    public synchronized void out(){        while (!flag){            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(Thread.currentThread().getName()+" consume num  is   : "+this.name);        flag = false;        this.notifyAll();    }}

執行結果如下:

Thread-0 produce num  : guyue--50325Thread-2 consume num  is   : guyue--50325Thread-1 produce num  : guyue--50326Thread-3 consume num  is   : guyue--50326Thread-0 produce num  : guyue--50327Thread-2 consume num  is   : guyue--50327Thread-1 produce num  : guyue--50328Thread-3 consume num  is   : guyue--50328

2、採用Lock-Condition方法實現如下:

class Product{    String name;    private int count = 1;    boolean flag = false;    Lock lock = new ReentrantLock();    Condition conditon = lock.newCondition();    public void set(String name){        try{            lock.lock();            while(flag){               conditon.await();            }            this.name = name +"--"+count++;            flag = true;            System.out.println(Thread.currentThread().getName()+" produce num  : "+this.name);            conditon.signalAll();        }catch (Exception e){        }finally {            lock.unlock();        }    }    public  void out(){        try{            lock.lock();            while(!flag){                conditon.await();            }            flag = false;            System.out.println(Thread.currentThread().getName()+" consumer num  is : "+this.name);            conditon.signalAll();        }catch (Exception e){        }finally {            lock.unlock();        }    }}

執行結果如下:

Thread-0 produce num  : guyue--20305Thread-3 consumer num  is : guyue--20305Thread-1 produce num  : guyue--20306Thread-2 consumer num  is : guyue--20306Thread-0 produce num  : guyue--20307Thread-3 consumer num  is : guyue--20307Thread-1 produce num  : guyue--20308Thread-2 consumer num  is : guyue--20308

Java多線程之死結與線程間通訊簡單案例

相關文章

聯繫我們

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