Java多線程中線程間的通信實(shí)例詳解
Java多線程中線程間的通信
一、使用while方式來(lái)實(shí)現(xiàn)線程之間的通信
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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素.."); 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("當(dāng)前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止.."); throw new RuntimeException(); } } } }, "t2"); t1.start(); t2.start(); } }
程序輸出:
當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. Exception in thread "t2" 當(dāng)前線程收到通知: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) 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素..
理解:線程Thread2不停地通過(guò)while語(yǔ)句檢測(cè)這個(gè)條件(list.size()==5)是否成立 ,從而實(shí)現(xiàn)了線程間的通信。但是這種方式會(huì)浪費(fèi)CPU資源。
二、wait notfiy 方法實(shí)現(xiàn)多線程中線程之間的通信
使用這種方式實(shí)現(xiàn)線程通信需要注意:wait和notify必須配合synchronized關(guān)鍵字使用,wait方法釋放鎖,notify方法不釋放鎖。并且在這個(gè)例子中必須是Thread2先執(zhí)行才可以。
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 實(shí)例化出來(lái)一個(gè) lock // 當(dāng)使用wait 和 notify 的時(shí)候 , 一定要配合著synchronized關(guān)鍵字去使用 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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素.."); Thread.sleep(500); if (list2.size() == 5) { System.out.println("已經(jīng)發(fā)出通知.."); //不釋放鎖,遇到size=5時(shí)還是繼續(xù)執(zhí)行 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 { //釋放鎖,讓其他線程執(zhí)行 lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("當(dāng)前線程:" + Thread.currentThread().getName() + "收到通知線程停止.."); throw new RuntimeException(); } } }, "t2"); t2.start(); t1.start(); } }
程序輸出:
當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 已經(jīng)發(fā)出通知.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程: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類(lèi)來(lái)實(shí)現(xiàn)多線程中線程之間的實(shí)時(shí)通信
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("當(dāng)前線程:" + Thread.currentThread().getName() + "添加了一個(gè)元素.."); Thread.sleep(500); if (list2.size() == 5) { System.out.println("已經(jīng)發(fā)出通知.."); 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("當(dāng)前線程:" + Thread.currentThread().getName() + "收到通知線程停止.."); throw new RuntimeException(); } }, "t2"); t2.start(); t1.start(); } }
程序輸出:
當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 已經(jīng)發(fā)出通知.. Exception in thread "t2" 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t2收到通知線程停止.. java.lang.RuntimeException at com.ietree.multithread.sync.ListAdd2$2.run(ListAdd2.java:56) at java.lang.Thread.run(Unknown Source) 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素.. 當(dāng)前線程:t1添加了一個(gè)元素..
四、使用多線程模擬一個(gè)隊(duì)列
package com.ietree.multithread.sync; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class MyQueue { // 1、定義一個(gè)盛裝元素集合 private LinkedList<Object> list = new LinkedList<Object>(); // 2、定義一個(gè)計(jì)數(shù)器 private AtomicInteger count = new AtomicInteger(); // 3、指定上限和下限 private final int minSize = 0; private final int maxSize; // 4、構(gòu)造方法初始化大小 public MyQueue(int size) { this.maxSize = size; } // 5、初始化一個(gè)對(duì)象用于加鎖 private Object lock = new Object(); // put(anObject): 把a(bǔ)nObject加到BlockingQueue里,如果BlockQueue沒(méi)有空間,則調(diào)用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續(xù). public void put(Object obj) { synchronized (lock) { if (count.get() == this.maxSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1、加入元素 list.add(obj); // 2、計(jì)數(shù)器累加 count.incrementAndGet(); // 3、通知(喚醒)另外一個(gè)線程 lock.notify(); System.out.println("新加入的元素為:" + obj); } } // take: 取走BlockingQueue里排在首位的對(duì)象,若BlockingQueue為空,阻斷進(jìn)入等待狀態(tài)直到BlockingQueue有新的數(shù)據(jù)被加入. public Object take() { Object ret = null; synchronized (lock) { while (count.get() == this.minSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1、做移除元素操作 ret = list.removeFirst(); // 2、計(jì)數(shù)器作遞減操作 count.decrementAndGet(); // 3、喚醒另外一個(gè)操作 lock.notify(); } return ret; } // 獲取長(zhǎng)度 public int getSize() { return this.count.get(); } public static void main(String[] args) { final MyQueue mq = new MyQueue(5); mq.put("a"); mq.put("b"); mq.put("c"); mq.put("d"); mq.put("e"); System.out.println("當(dāng)前容器的長(zhǎng)度:" + mq.getSize()); Thread t1 = new Thread(new Runnable() { @Override public void run() { mq.put("f"); mq.put("g"); } }, "t1"); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { Object o1 = mq.take(); System.out.println("移除的元素為:" + o1); Object o2 = mq.take(); System.out.println("移除的元素為:" + o2); } }, "t2"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); } }
程序輸出:
新加入的元素為:a 新加入的元素為:b 新加入的元素為:c 新加入的元素為:d 新加入的元素為:e 當(dāng)前容器的長(zhǎng)度:5 移除的元素為:a 移除的元素為:b 新加入的元素為:f 新加入的元素為:g
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Java如何實(shí)現(xiàn)驗(yàn)證碼驗(yàn)證功能
這篇文章主要教大家如何實(shí)現(xiàn)Java驗(yàn)證碼驗(yàn)證功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02Java關(guān)于List集合去重方案詳細(xì)介紹
實(shí)際項(xiàng)目開(kāi)發(fā)中,很多業(yè)務(wù)場(chǎng)景下都會(huì)遇見(jiàn)集合去重。在說(shuō)到List集合去重之前,首先我們回顧下普通類(lèi)型的list如何去重2021-09-09關(guān)于MyBatis Plus中使用or和and問(wèn)題
這篇文章主要介紹了關(guān)于MyBatis Plus中使用or和and問(wèn)題,需要的朋友可以參考下2020-12-12springboot+vue實(shí)現(xiàn)Minio文件存儲(chǔ)的示例代碼
本文主要介紹了springboot+vue實(shí)現(xiàn)Minio文件存儲(chǔ)的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02Mybatis原始執(zhí)行方式Executor代碼實(shí)例
這篇文章主要介紹了Mybatis原始執(zhí)行方式Executor代碼實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07SpringCloud聲明式Feign客戶端調(diào)用工具使用
這篇文章主要為大家介紹了SpringCloud聲明式Feign客戶端調(diào)用工具使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08java實(shí)現(xiàn)多線程文件的斷點(diǎn)續(xù)傳
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)多線程文件的斷點(diǎn)續(xù)傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06java實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)象棋游戲
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單網(wǎng)絡(luò)象棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12