国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java多線程通信wait()和notify()代碼實例

瀏覽:143日期:2022-09-03 11:05:03

1.wait()方法和sleep()方法:

wait()方法在等待中釋放鎖;sleep()在等待的時候不會釋放鎖,抱著鎖睡眠。

2.notify():

隨機喚醒一個線程,將等待隊列中的一個等待線程從等待隊列中移到同步隊列中。

代碼如下

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(); }}

在該案例中,實現(xiàn)一問一答的線程同步通信。當方法中開啟了wait()方法后,通過改變flag的值來喚醒線程進而實行另一個方法。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Java
相關文章:
主站蜘蛛池模板: 桃江县| 双流县| 伊吾县| 庆安县| 舒城县| 洪江市| 博湖县| 新乐市| 太白县| 巴中市| 阿合奇县| 沽源县| 翁牛特旗| 容城县| 鄢陵县| 沁源县| 静宁县| 石棉县| 图木舒克市| 桃源县| 寿阳县| 获嘉县| 陕西省| 丰都县| 汉沽区| 南汇区| 正阳县| 牟定县| 格尔木市| 卓尼县| 迁安市| 威远县| 海南省| 大冶市| 西乡县| 大城县| 南京市| 靖远县| 安康市| 博湖县| 诸暨市|