视频下载地址:http://www.itheima.com/news/2012821/24cf70b28ae2.shtml
交通灯管理系统,主要有三个类,路Road 灯 Lamp 灯控制类 LampController
Road提供模拟汽车不断上路的过程 和 放行车辆的过程
Lamp提供灯光变换的功能
LampController 控制灯光的变换
package com.lihao.traffic;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Road {
private List vechicles =new ArrayList();
private String name=null;
public Road(String name){
this.name=name;
//模拟汽车不断上路的过程
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
@Override
public void run() {
for(int i=1;i<1000;i++){
try {
Thread.sleep((new Random().nextInt(10)+1)*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vechicles.add(Road.this.name+"_"+i);
}
}
});
//每隔一秒检查对应的灯是否为绿灯,如果是放行一辆车
//在一秒之后,每隔一秒执行
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
if(vechicles.size()>0){
boolean lighted=Lamp.valueOf(Road.this.name).isLighted();
if(lighted){
System.out.println(vechicles.remove(0)+" is traversing");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
package com.lihao.traffic;
public enum Lamp {
E2W("W2E","S2N",false),S2N("N2S","E2S",false),E2S("W2N","S2W",false),S2W("N2E","E2W",false),
W2E(null,null,false),N2S(null,null,false),W2N(null,null,false),N2E(null,null,false),
E2N(null,null,true),N2W(null,null,true),W2S(null,null,true),S2E(null,null,true);
private Lamp(String opposite,String next,boolean lighted){
this.opposite=opposite;
this.next=next;
this.lighted=lighted;
}
private String opposite;
private String next;
private boolean lighted;
public boolean isLighted(){
return lighted;
}
//某个灯变绿时,对应的灯也变绿
public void light(){
this.lighted=true;
if(opposite!=null){
Lamp.valueOf(opposite).light();
}
System.out.println(name()+" lamp is green 下面总共应该有6个方向会有车辆行驶!!");
}
//某个灯变红时,对应的灯也变红,下个灯变亮
public Lamp blackOut(){
this.lighted=false;
if(opposite!=null){
Lamp.valueOf(opposite).blackOut();
}
Lamp nextLamp = null;
if(next!=null){
nextLamp = Lamp.valueOf(next);
System.out.println("绿灯从" + name() + "-------->切换为" + next);
nextLamp.light();
}
return nextLamp;
}
}
package com.lihao.traffic;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LampController {
private Lamp currentLamp;
public LampController(){
currentLamp = Lamp.E2W;
currentLamp.light();
//红灯绿灯间隔时间为10秒
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
currentLamp = currentLamp.blackOut();
}
},
10,
10,
TimeUnit.SECONDS);
}
}