java 中多線程之間的通訊之等待喚醒機制

來源:互聯網
上載者:User

標籤:

wait

notify ()

nitifyAll ()

 

都使用在同步中,因為要對持有監視器(鎖)的線程操作

所以要使用在同步中,因為只有同步才具有鎖

 

為什麼這些操作線程的方法要定義object類中呢

因為這些方法在操作同步中線程時。都必須要標識他們所操作線程只有的鎖

只有同一個鎖上的被等待線程,可以被同一個鎖上的notify喚醒

不可以對不同鎖中的線程進行喚醒

也就是說,等待和喚醒必須是同一個鎖

而鎖可以使任意對象,所以可以被任意對象調用的方法定義object類中 

 1 class Res 2 { 3     String name; 4     String  sex; 5     boolean flag = false; 6 } 7  8 class Input implements Runnable 9 {10     private Res r ;11     Input (Res r){12     this.r = r;13     }14     public void run (){15         int x = 0;16         while (true)17         {18             synchronized (r) {19                 if (r.flag)20                     try {r.wait();}catch(Exception e){}21                     if (x==0){22                         r.name = "java";23                         r.sex = "man";24                     }25                     else26                     {27                         r.name = "傑克";28                         r.sex = "女女vn";29                         30                     }31                     x = (x+1)%2;32                     r.flag = true;33                     r.notify();34                     35                 }36             }37             38         }            39         40     }41     42 43 44 class Output implements Runnable45 {46        private Res r;    47        Output (Res r){48            49            this.r = r;50        }51        public void run (){52            while (true){53                synchronized(r){54                    55                    if (!r.flag)56                        57                        try {r.wait();}catch (Exception e){}58                        System.out.println (r.name+"..."+r.sex);59                        r.flag = false;60                        r.notify();61                        62                    }63                }64                65            }66            67        }68 69 public class InputOutputDemo {70 71     public static void main(String[] args) {72         // TODO Auto-generated method stub73         74          System.out.println ("ddddd");75         Res r = new Res ();76         Input input = new Input (r);77         Output output = new Output (r);78         79 80         Thread t1 = new Thread (input);81         Thread t2 = new Thread (output);82         t1.start();83         t2.start();84     }85 86 }

 

java 中多線程之間的通訊之等待喚醒機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.