十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
小編給大家分享一下java多線程wait()和notify()如何使用,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供莊浪網(wǎng)站建設(shè)、莊浪做網(wǎng)站、莊浪網(wǎng)站設(shè)計(jì)、莊浪網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、莊浪企業(yè)網(wǎng)站模板建站服務(wù),十載莊浪做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
注:wait()和notify()應(yīng)當(dāng)用在synchronized內(nèi) package com.test; import java.util.ArrayList; public class ThreadWaitTeste { public static void main(String[] args) { ArrayListar = new ArrayList (); Product p = new Product(ar); Consumer c = new Consumer(ar); Thread t1 = new Thread(p); Thread t2 = new Thread(c); t1.start(); t2.start(); } } class Product implements Runnable{ ArrayList array; public Product(ArrayList array){ this.array= array; } public void run() { while (true){ synchronized(array){ if(this.array.size()<5){ this.array.add("test!"); this.array.add("test!"); this.array.add("test!"); this.array.add("test!"); System.out.println("Product size : "+array.size()); }else{ System.out.println("Product wait size : "+array.size()+"數(shù)量少于5,等待......"); try { array.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } class Consumer implements Runnable{ ArrayList array; public Consumer(ArrayList array){ this.array= array; } public void run() { while(true){ synchronized(array){ if(this.array.size()>=5){ this.array.remove(1); System.out.println("Consumer size : "+array.size()); }else{ try { array.notifyAll(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }
看完了這篇文章,相信你對“java多線程wait()和notify()如何使用”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!