Java多線程通信wait()和notify()代碼實(shí)例
1.wait()方法和sleep()方法:
wait()方法在等待中釋放鎖;sleep()在等待的時(shí)候不會(huì)釋放鎖,抱著鎖睡眠。
2.notify():
隨機(jī)喚醒一個(gè)線程,將等待隊(duì)列中的一個(gè)等待線程從等待隊(duì)列中移到同步隊(duì)列中。
代碼如下
public class Demo_Print { public static void main(String[] args) { Print p = new Print(); new Thread() { public void run() {while (true) { p.print1();} }; }.start(); new Thread() { public void run() {while (true) { p.print2();} }; }.start(); }}class Print { int flag = 1; public synchronized void print1() { if (flag != 1) { try {this.wait(); } catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace(); } } System.out.print('你'); System.out.print('好'); System.out.print('嗎????????????'); System.out.println(); flag = 2; this.notify(); } public synchronized void print2() { if (flag != 2) { try {this.wait(); } catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace(); } } System.out.print('我'); System.out.print('好'); System.out.println(); flag = 1; this.notify(); }}
在該案例中,實(shí)現(xiàn)一問一答的線程同步通信。當(dāng)方法中開啟了wait()方法后,通過改變flag的值來喚醒線程進(jìn)而實(shí)行另一個(gè)方法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python自動(dòng)化之定位方法大殺器xpath2. python調(diào)用百度API實(shí)現(xiàn)人臉識(shí)別3. 如何基于Python和Flask編寫Prometheus監(jiān)控4. Python Selenium破解滑塊驗(yàn)證碼最新版(GEETEST95%以上通過率)5. python 寫一個(gè)文件分發(fā)小程序6. 用python對oracle進(jìn)行簡單性能測試7. Python 利用flask搭建一個(gè)共享服務(wù)器的步驟8. Python QT組件庫qtwidgets的使用9. Vue3中使用this的詳細(xì)教程10. Python中Anaconda3 安裝gdal庫的方法
