代码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 }