Java通過(guò)wait()和notifyAll()方法實(shí)現(xiàn)線程間通信
本文實(shí)例為大家分享了Java實(shí)現(xiàn)線程間通信的具體代碼,供大家參考,具體內(nèi)容如下
Java代碼(使用了2個(gè)內(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(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java流操作之?dāng)?shù)據(jù)流實(shí)例代碼
這篇文章主要介紹了Java流操作之?dāng)?shù)據(jù)流實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01SpringBoot實(shí)現(xiàn)yml配置文件為變量賦值
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)yml配置文件為變量賦值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02關(guān)于mybatis-plus-generator的簡(jiǎn)單使用示例詳解
在springboot項(xiàng)目中集成mybatis-plus是很方便開發(fā)的,最近看了一下plus的文檔,簡(jiǎn)單用一下它的代碼生成器,接下來(lái)通過(guò)實(shí)例代碼講解關(guān)于mybatis-plus-generator的簡(jiǎn)單使用,感興趣的朋友跟隨小編一起看看吧2024-03-03基于SpringBoot實(shí)現(xiàn)自定義插件的流程詳解
在SpringBoot中,插件是一種擴(kuò)展機(jī)制,它可以幫助我們?cè)趹?yīng)用程序中快速地添加一些額外的功能,在本文中,我們將介紹如何使用 SpringBoot實(shí)現(xiàn)自定義插件,需要的朋友可以參考下2023-06-06springboot內(nèi)置tomcat調(diào)優(yōu)并發(fā)線程數(shù)解析
這篇文章主要介紹了springboot內(nèi)置tomcat調(diào)優(yōu)并發(fā)線程數(shù)解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12java調(diào)用mysql存儲(chǔ)過(guò)程實(shí)例分析
這篇文章主要介紹了java調(diào)用mysql存儲(chǔ)過(guò)程的方法,以實(shí)例形式較為詳細(xì)的分析了mysql數(shù)據(jù)庫(kù)的建立和存儲(chǔ)過(guò)程的實(shí)現(xiàn)方法,需要的朋友可以參考下2015-06-06