代碼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 //初始狀態設為紅燈,且紅燈時常為10s 14 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 //當前車輛睡眠1s 16 c.sleep(1000); 17 c.start(); 18 } 19 } 20 }