public class LampController {
private Lamp currentLamp;
public LampController(){
currentLamp=Lamp.S2N;
currentLamp.Light();
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
System.out.println("开始运作");
currentLamp.BlackOut();
public class Road {
//定义一个车属性代表路上通行的车,车属性为一个集合代表路上车的数量
List<String> vehicle=new ArrayList<>();
//定义路的名字,这里的名字主要是指路上车的行车方向
private String name=null;
//定义类Road类的构造器,传入一个name属性,并初始化
public Road( String name){
this.name=name;
//使用Executros工厂产生一个单线程线程池pool,该线程池中传入的Runnable模拟不断有车开到路上的情景。
//当路上的车小于1000辆时,通过线程的休眠来实现每隔一段时间(10秒以内)向路下增加一辆车
ExecutorService pool=Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
public void run(){
for(int i=1;i<1000;i++){
try{Thread.sleep((new Random().nextInt(10)+1)*1000);}
catch(InterruptedException e){
e.printStackTrace();
}
vehicle.add(Road.this.name+"_"+i);
}
}
});
/*定义一个延迟执行的线程池timer,模拟当绿灯亮时每隔一段时间就让一辆车,这里是的时
间间隔是1秒**/
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
if(vehicle.size()>0){
boolean lighted=Lamp.valueOf(Road.this.name).isLighted();
if(lighted){
System.out.println(vehicle.remove(0)+"is travelling");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
package com.isoftstone.interview.traffic;
public class MainClass {
public static void main(String[] args){
String[] directions=new String[]{"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"};
for(int i=0;i<directions.length;i++){new Road(directions[i]);}
new LampController();