JAVA中的多線程(六)

來源:互聯網
上載者:User

標籤:als   try   static   not   class   rcu   zed   dem   this   

生產者消費者

 1 class Resource 2 { 3     private String name; 4     private int count = 1; 5     private boolean flag = false; 6      7     public synchronized void set(String name) 8     { 9         while(flag)10             try{this.wait();}catch(Exception e){}11         this.name = name+"--"+count++;12         System.out.println(Thread.currentThread().getName()+"...生產者..."+this.name);13         flag = true;14         this.notifyAll();15     }16     17     public synchronized void out()18     {19         while(!flag)20             try{this.wait();}catch(Exception e){}21         System.out.println(Thread.currentThread().getName()+"...消費者..."+this.name);22         flag = false;23         this.notifyAll();24     }25 }26 27 class Producer implements Runnable28 {29     private Resource res;30     31     Producer(Resource res)32     {33         this.res = res;34     }35     36     public void run()37     {38         while(true)39         {40             res.set("+TT+");41         }42     }43 }44 45 class Customer implements Runnable46 {47     private Resource res;48     49     Customer(Resource res)50     {51         this.res = res;52     }53     54     public void run()55     {56         while(true)57         {58             res.out();59         }60     }61 }62 class ProducerCustomerDemo63 {64     public static void main(String[] args)65     {66         Resource r = new Resource();67         68         Producer pro = new Producer(r);69         Customer con = new Customer(r);70         71         Thread t1 = new Thread(pro);72         Thread t2 = new Thread(con);73         74         t1.start();75         t2.start();76     }77 }
View Code

 

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.