Java通過wait()和notifyAll()方法實現(xiàn)線程間通信
更新時間:2017年04月10日 09:04:50 作者:FrankYou
這篇文章主要為大家詳細介紹了Java通過wait()和notifyAll()方法實現(xiàn)線程間通信的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Java實現(xiàn)線程間通信的具體代碼,供大家參考,具體內(nèi)容如下
Java代碼(使用了2個內(nèi)部類):
package Threads; import java.util.LinkedList; /** * Created by Frank */ public class ProdCons { protected LinkedList<Object> list = new LinkedList<>(); protected int max; protected boolean done = false; public static void main(String[] args) throws InterruptedException { ProdCons prodCons = new ProdCons(100, 3, 4); Thread.sleep(5 * 1000); synchronized (prodCons.list) { prodCons.done = true; try { prodCons.notifyAll(); } catch (Exception ex) { } } } private ProdCons(int maxThreads, int nP, int nC) { this.max = maxThreads; for (int i = 0; i < nP; i++) { new Producer().start(); } for (int i = 0; i < nC; i++) { new Consumer().start(); } } class Producer extends Thread { public void run() { while (true) { Object justProduced = null; try { justProduced = getObj(); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (list) { while (list.size() == max) { try { list.wait(); } catch (InterruptedException e) { System.out.println("Producer INTERRUPTED"); } } list.addFirst(justProduced); list.notifyAll(); System.out.println("Produced 1;List size now " + list.size()); if (done) { break; } } } } } class Consumer extends Thread { public void run() { while (true) { Object object = null; synchronized (list) { if (list.size() == 0) { try { list.wait(); } catch (InterruptedException e) { System.out.println("Consumer INTERRUPTED"); } } if (list.size() > 0) { object = list.removeLast(); } list.notifyAll(); System.out.println("List size now " + list.size()); if (done) { break; } } if (null != object) { System.out.println("Consuming object " + object); } } } } private Object getObj() throws InterruptedException { Thread.sleep(1000); return new Object(); } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot實現(xiàn)yml配置文件為變量賦值
這篇文章主要介紹了SpringBoot實現(xiàn)yml配置文件為變量賦值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02關于mybatis-plus-generator的簡單使用示例詳解
在springboot項目中集成mybatis-plus是很方便開發(fā)的,最近看了一下plus的文檔,簡單用一下它的代碼生成器,接下來通過實例代碼講解關于mybatis-plus-generator的簡單使用,感興趣的朋友跟隨小編一起看看吧2024-03-03基于SpringBoot實現(xiàn)自定義插件的流程詳解
在SpringBoot中,插件是一種擴展機制,它可以幫助我們在應用程序中快速地添加一些額外的功能,在本文中,我們將介紹如何使用 SpringBoot實現(xiàn)自定義插件,需要的朋友可以參考下2023-06-06springboot內(nèi)置tomcat調(diào)優(yōu)并發(fā)線程數(shù)解析
這篇文章主要介紹了springboot內(nèi)置tomcat調(diào)優(yōu)并發(fā)線程數(shù)解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12