Java 線程間通訊

來源:互聯網
上載者:User

標籤:儲存   ace   public   imp   tput   資源   run   package   str   

/*線程間通訊:多個線程在處理同一資源,但是任務卻不同。*/package com.cwcec.test;class Input implements Runnable{       Resource r;       public Input(Resource r)       {           this.r = r;       }       public void run()       {           int x = 0;           while(true)           {               synchronized (r)               {                   if(x == 0)                      {                          r.name = "Mike";                          r.sex = "nan";                      }                      else                      {                       r.name = "麗麗";                       r.sex = "女";                   }                      x = (x + 1) % 2;            }                          }       }}class Output implements Runnable{    Resource r;    public Output(Resource r)    {        this.r = r;    }    public void run()    {        while(true)        {            synchronized (r)            {                System.out.println(r.name + "..." + r.sex);            }                    }    }}class Resource{   String name;   String sex;}public class Person {    public static void main(String[] args)    {                Resource r = new Resource();        Input in = new Input(r);        Output output = new Output(r);                Thread t1 = new Thread(in);        Thread t2 = new Thread(output);                t1.start();        t2.start();    }}
Output:Mike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nan麗麗...女麗麗...女麗麗...女麗麗...女麗麗...女麗麗...女麗麗...女 

 

/* 等待/喚醒機制。  涉及的方法: 1,wait(): 讓線程處於凍結狀態,被wait的線程會被儲存到線程池中。2,notify():喚醒線程池中一個線程(任意).3,notifyAll():喚醒線程池中的所有線程。 這些方法都必須定義在同步中。因為這些方法是用於操作線程狀態的方法。必須要明確到底操作的是哪個鎖上的線程。  為什麼操作線程的方法wait notify notifyAll定義在了Object類中?  因為這些方法是監視器的方法。監視器其實就是鎖。鎖可以是任意的對象,任意的對象調用的方式一定定義在Object類中。
class Input implements Runnable{       Resource r;       public Input(Resource r)       {           this.r = r;       }       public void run()       {           int x = 0;           while(true)           {               synchronized (r)               {                   if(r.flag)                   {                       try {                        r.wait();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                   }                                      if(x == 0)                      {                          r.name = "Mike";                          r.sex = "nan";                      }                      else                      {                       r.name = "麗麗";                       r.sex = "女";                   }                                            r.flag = true;                      r.notify();            }               x = (x + 1) % 2;                          }       }}class Output implements Runnable{    Resource r;    public Output(Resource r)    {        this.r = r;    }    public void run()    {        while(true)        {            synchronized (r)            {                if(!r.flag)                    try {                        r.wait();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                System.out.println(r.name + "..." + r.sex);                r.flag = false;                r.notify();            }        }    }}class Resource{   String name;   String sex;   boolean flag = false;}public class Person {    public static void main(String[] args)    {                Resource r = new Resource();        Input in = new Input(r);        Output output = new Output(r);                Thread t1 = new Thread(in);        Thread t2 = new Thread(output);                t1.start();        t2.start();    }}
Output:Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan

 

  程式最佳化:
class Input implements Runnable{       Resource r;       public Input(Resource r)       {           this.r = r;       }       public void run()       {           int x = 0;           while(true)           {                   if(x == 0)                      {                          r.set("Mike", "nan");                      }                      else                      {                          r.set("麗麗", "女");                   }               x = (x + 1) % 2;                          }       }}class Output implements Runnable{    Resource r;    public Output(Resource r)    {        this.r = r;    }    public void run()    {        while(true)        {             r.out();        }    }}class Resource{   private String name;   private String sex;   private boolean flag = false;   public synchronized void set(String name,String sex)   {       if(flag)        try {            this.wait();        } catch (InterruptedException e) {            // TODO 自動產生的 catch 塊            e.printStackTrace();        }       this.name = name;       this.sex = sex;       flag = true;       this.notify();   }      public synchronized void out()   {       if(!flag)           try {                this.wait();            } catch (InterruptedException e) {                // TODO 自動產生的 catch 塊                e.printStackTrace();            }       System.out.println(name + "...+" + sex);       flag = false;       this.notify();   }   }public class Person {    public static void main(String[] args)    {                Resource r = new Resource();        Input in = new Input(r);        Output output = new Output(r);                Thread t1 = new Thread(in);        Thread t2 = new Thread(output);                t1.start();        t2.start();    }}
Output:Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan麗麗...女Mike...nan

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.