標籤: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多線程類比紅綠燈案例