线程间的通信 设置线程等待与线程唤醒
生活随笔
收集整理的這篇文章主要介紹了
线程间的通信 设置线程等待与线程唤醒
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
代碼實現上述框圖:
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
總結
以上是生活随笔為你收集整理的线程间的通信 设置线程等待与线程唤醒的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Git 初始化版本库
- 下一篇: 简记用ArcGIS处理某项目需求中数据的