日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程间的通信 设置线程等待与线程唤醒

發布時間:2023/12/2 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程间的通信 设置线程等待与线程唤醒 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

代碼實現上述框圖:

1 //等待喚醒機制 2 3 /* 4 wait(),notify(),notifyAll()必須用在同步中,因為同步中才有鎖。 5 指明讓持有那個鎖的線程去等待或被喚醒,例如object.wait(),表明讓持有object這把鎖的線程等待。 6 7 wait():讓線程進入等待狀態,就是把線程放入了線程池。 8 notify():喚醒線程池中的任意一個線程(持有特定鎖的任意一個線程)。 9 notifyAll():喚醒所有線程。 10 11 wait(),notify(),notifyAll()為什么定義在Object中? 12 鎖可以是任意的對象,任意對象都可以調用的方法需要定義在Object中。 13 */ 14 15 16 //描述數據 17 class Resource 18 { 19 public String name; 20 public String gender; 21 public boolean flag; //添加標記,默認為false;標志位的用途:例如:Input存完一組數據可能繼續持有CPU,存完后將flag置反,則Input無法繼續存入數據。 22 public Resource(){} 23 } 24 25 //描述輸入任務 26 class Input implements Runnable 27 { 28 private Resource res; 29 public Input(Resource res) 30 { 31 this.res = res; 32 } 33 public void run() 34 { 35 int i = 1; 36 while(true) 37 { 38 synchronized(res) //加同步鎖① 39 { 40 if(res.flag) 41 { 42 //等待的線程會放棄鎖,跟sleep不同,sleep的線程仍然擁有鎖。 43 try{res.wait();}catch(InterruptedException e){e.printStackTrace();} //判斷flag標志,先判斷該不該存,如果為true,放棄CPU。 44 } 45 if(i==1) 46 { 47 res.name = "豬小明"; 48 res.gender = "男"; 49 } 50 else 51 { 52 res.name = "腿腿"; 53 res.gender = "女"; 54 } 55 i=(++i)%2; //0、1切換 56 res.flag = true; 57 res.notify(); //喚醒對方,允許空喚醒。 58 //try{res.wait();}catch(InterruptedException e){e.printStackTrace();} 59 } 60 } 61 } 62 } 63 64 //描述輸出任務 65 class Output implements Runnable 66 { 67 private Resource res; 68 public Output(Resource res) 69 { 70 this.res = res; 71 } 72 public void run() 73 { 74 while(true) 75 { 76 synchronized(res) //加同步鎖②,①處和此處為同一把鎖! 77 { 78 if(!res.flag) 79 { 80 try{res.wait();}catch(InterruptedException e){e.printStackTrace();} //判斷flag標志,先判斷該不該存,如果為false,放棄CPU。 81 } 82 System.out.println(res.name + "....." + res.gender); 83 res.flag = false; 84 res.notify(); //喚醒對方 85 //try{res.wait();}catch(InterruptedException e){e.printStackTrace();} 86 } 87 } 88 } 89 } 90 91 class TestDengdai 92 { 93 public static void main(String[] args) 94 { 95 //創建資源 96 Resource res = new Resource(); 97 //創建輸入任務 98 Input input = new Input(res); 99 //創建輸出任務 100 Output output = new Output(res); 101 //創建輸入線程 102 Thread t1 = new Thread(input); 103 //創建輸出線程 104 Thread t2 = new Thread(output); 105 //啟動線程 106 t1.start(); 107 t2.start(); 108 109 } 110 }

?

?

?

?

上述代碼實現存入一個輸出一個的運行效果:

轉載于:https://www.cnblogs.com/tzc1024/p/6040700.html

總結

以上是生活随笔為你收集整理的线程间的通信 设置线程等待与线程唤醒的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。