java多線程類比紅綠燈案例

來源:互聯網
上載者:User

標籤:ack   thread   int   java多線程   根據   出錯   min   i+1   pack   

代碼Lighter.java:

 1 package pack1; 2 /** 3  * 燈線程 4  * @author Administrator 5  * 6  */ 7 public class Lighter extends Thread{ 8 //代表燈當前的狀態(這裡只考慮紅綠兩種狀態) 9 public String state;10 public void run(){11     while (true){12         try {13             //初始狀態設為紅燈,且紅燈時常為10s14             state = "red";15             System.out.println("lighter:現在是紅燈,靜止車輛通行");16             Thread.sleep(10*1000);17             //10s後燈變綠,設綠燈時間位5秒18             state = "green";19             System.out.println("lighter:現在變綠燈了,車輛可以通行了。");20             Lighter.sleep(5*1000);21         } catch (InterruptedException e) {22             System.out.println("出錯了:"+e);23         }24     }25 }26 }

代碼Car.java

package pack1;/** * 車輛線程 * @author Administrator * */public class Car extends Thread{String name="";//燈作為私人變數,車輛根據燈的狀態決定是否要停止private Lighter lighter;public Car(String name,Lighter l){    this.name=name;    this.lighter=l;}public void run(){    if (lighter.state.equals("red")){        System.out.println(this.name+":等待中");    }else{                System.out.println(this.name+":通過了紅綠燈");    }}}

測試代碼RglightTest.java

 1 package pack1; 2 /** 3  * 紅綠燈測試代碼 4  * @author Administrator 5  * 6  */ 7 public class RglightTest { 8 public static void main(String[] args) throws InterruptedException { 9     Lighter l=new Lighter();10         //紅綠燈開始運行11     l.start();12         //產生20個車輛,依次通過紅綠燈13     for(int i=0;i<20;i++){14         Car c=new Car("car"+i+1,l);15                 //當前車輛睡眠1s16         c.sleep(1000);17         c.start();18     }19 }20 }

 

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.