您的位置:首页 > 职场人生

黑马程序员 java基础加强之交通灯管理系统

2013-05-16 17:31 549 查看




public class Road {
private List<String> vehicles = new ArrayList<String>();
private String name;
public Road(String name){
this.name = name;
//线程池,随机生成车辆
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
public void run(){
for (int i = 1; i < 1000; i++) {
try {
//随机休眠0-9秒。
Thread.sleep((new Random().nextInt(10)) * 1000);
//添加一辆车。方法中内部类访问外部的成员变量需要加final,或者可以Road.name.这里因为和局部变量冲突,所以需要加this
vehicles.add(Road.this.name + "路上第" + i+ "辆车");//
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
//定时器,用来定时移除集合中的元素,也就是路上的车辆。
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){//第一个参数,线程
public void run(){
boolean lighted = Lamp.valueOf(Road.this.name).isGreen();
if(vehicles.size() > 0){
if(lighted){
System.out.println(vehicles.remove(0) + "通过");
}
}
}
},
, //第二个参数,初始延迟
, //第三个参数,延迟时期
TimeUnit.SECONDS//第四个参数,延迟单位
);
}
}


  

public enum Lamp {
//枚举表示各个方向的信号灯
S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false),
//该行信号灯是上一行的相反方向的灯
N2S(null,null,false),N2E(null,null,false),W2E(null,null,false),W2N(null,null,false),
//该行信号灯是直接右转的等,实际情况中没有,但是为了统一设计,这里作为隐性的灯,保持常亮状态
S2E(null,null,true),E2N(null,null,true),N2W(null,null,true),W2S(null,null,true);
//相反方向的等的引用,因为上面枚举对象中要用到其他枚举对象,如果直接传对象是不行的,所以用灯名作为参数
private String opposite;
//下一个灯名
private String next;
private boolean lighted;
public boolean isGreen(){
return lighted;
}
private Lamp(String opposite, String nextLamp, boolean lighted){
this.opposite = opposite;
this.next = nextLamp;
this.lighted = lighted;
}
//灯变绿,同时将相反的灯也变绿
public void changeGreen(){
this.lighted = true;
if(opposite != null){
Lamp.valueOf(opposite).changeGreen();
}
System.out.println(name() + "灯变绿了,下面总共有6个方向可以看到汽车穿过");
}
//灯变红,同时将相反的灯变红,再将下一个灯变绿,并返回下一个灯。
public Lamp changeRed(){
this.lighted = false;
if(opposite != null){
Lamp.valueOf(opposite).changeRed();
}
Lamp nextLamp = null;
if(next != null){
nextLamp = Lamp.valueOf(next);
System.out.println("绿灯从" + name() + "切换为" + next);
nextLamp.changeGreen();
}
return nextLamp;
}
}


  

public class LampController {
//当前灯
private Lamp currentLamp;
public LampController(){
//当前灯从任意一个开始
currentLamp = Lamp.S2N;
currentLamp.changeGreen();
//每隔30秒将当前灯变红,并将下一个灯变绿
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
currentLamp = currentLamp.changeRed();//返回下一个灯作为当前灯
}
},
,
,
TimeUnit.SECONDS
);
}
}


  

public class MainClass {
public static void main(String[] args) {
//产生12个方向的路线
String [] roads = new String[]{
"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"
};
for (int i = 0; i < roads.length; i++) {
new Road(roads[i]);
}
//启动信号灯控制系统
new LampController();
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: