Java多線程中線程間的通訊,java多線程

來源:互聯網
上載者:User

Java多線程中線程間的通訊,java多線程
一、使用while方式來實現線程之間的通訊

package com.ietree.multithread.sync;import java.util.ArrayList;import java.util.List;public class MyList {        private volatile static List list = new ArrayList();    public void add() {        list.add("apple");    }    public int size() {        return list.size();    }    public static void main(String[] args) {        final MyList list1 = new MyList();        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    for (int i = 0; i < 10; i++) {                        list1.add();                        System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");                        Thread.sleep(500);                    }                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }, "t1");        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    if (list1.size() == 5) {                        System.out.println("當前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止..");                        throw new RuntimeException();                    }                }            }        }, "t2");        t1.start();        t2.start();    }}

程式輸出:

當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..Exception in thread "t2" 當前線程收到通知:t2 list size = 5 線程停止..java.lang.RuntimeException    at com.ietree.multithread.sync.MyList$2.run(MyList.java:43)    at java.lang.Thread.run(Unknown Source)當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..

理解:線程Thread2不停地通過while語句檢測這個條件(list.size()==5)是否成立 ,從而實現了線程間的通訊。但是這種方式會浪費CPU資源。

二、wait notfiy 方法實現多線程中線程之間的通訊

使用這種方式實現線程通訊需要注意:wait和notify必須配合synchronized關鍵字使用,wait方法釋放鎖,notify方法不釋放鎖。並且在這個例子中必須是Thread2先執行才可以。

package com.ietree.multithread.sync;import java.util.ArrayList;import java.util.List;public class ListAdd3 {    private volatile static List list = new ArrayList();    public void add() {        list.add("apple");    }    public int size() {        return list.size();    }    public static void main(String[] args) {        final ListAdd2 list2 = new ListAdd2();        // 1 執行個體化出來一個 lock        // 當使用wait 和 notify 的時候 , 一定要配合著synchronized關鍵字去使用        final Object lock = new Object();        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    synchronized (lock) {                        for (int i = 0; i < 10; i++) {                            list2.add();                            System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");                            Thread.sleep(500);                            if (list2.size() == 5) {                                System.out.println("已經發出通知..");
//不釋放鎖,遇到size=5時還是繼續執行 lock.notify(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { if (list2.size() != 5) { try {
//釋放鎖,讓其他線程執行 lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("當前線程:" + Thread.currentThread().getName() + "收到通知線程停止.."); throw new RuntimeException(); } } }, "t2"); t2.start(); t1.start(); }}

程式輸出:

當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..已經發出通知..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t2收到通知線程停止..Exception in thread "t2" java.lang.RuntimeException    at com.ietree.multithread.sync.ListAdd3$2.run(ListAdd3.java:59)    at java.lang.Thread.run(Unknown Source)
三、使用CountDownLatch類來實現多線程中線程之間的即時通訊
package com.ietree.multithread.sync;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;public class ListAdd2 {    private volatile static List list = new ArrayList();    public void add() {        list.add("apple");    }    public int size() {        return list.size();    }    public static void main(String[] args) {        final ListAdd2 list2 = new ListAdd2();        final CountDownLatch countDownLatch = new CountDownLatch(1);        Thread t1 = new Thread(new Runnable() {            @Override            public void run() {                try {                    for (int i = 0; i < 10; i++) {                        list2.add();                        System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");                        Thread.sleep(500);                        if (list2.size() == 5) {                            System.out.println("已經發出通知..");                            countDownLatch.countDown();                        }                    }                    // }                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }, "t1");        Thread t2 = new Thread(new Runnable() {            @Override            public void run() {                if (list2.size() != 5) {                    try {                        countDownLatch.await();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                System.out.println("當前線程:" + Thread.currentThread().getName() + "收到通知線程停止..");                throw new RuntimeException();            }        }, "t2");        t2.start();        t1.start();    }}

程式輸出:

當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..已經發出通知..Exception in thread "t2" 當前線程:t1添加了一個元素..當前線程:t2收到通知線程停止..java.lang.RuntimeException    at com.ietree.multithread.sync.ListAdd2$2.run(ListAdd2.java:56)    at java.lang.Thread.run(Unknown Source)當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..當前線程:t1添加了一個元素..

 

聯繫我們

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