本文實(shí)例為大家分享了Java實(shí)現(xiàn)線程間通信的具體代碼,供大家參考,具體內(nèi)容如下
創(chuàng)新互聯(lián)主要從事成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)深澤,10多年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792
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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
新聞名稱:Java通過wait()和notifyAll()方法實(shí)現(xiàn)線程間通信
本文URL:http://chinadenli.net/article12/jggegc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、虛擬主機(jī)、移動網(wǎng)站建設(shè)、靜態(tài)網(wǎng)站、關(guān)鍵詞優(yōu)化、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)