关于JDK5交通灯模拟控制系统
为了方便广大程序猿交流和学习,下面小编准备了关于JDK5交通灯模拟控制系统,欢迎大家参考!
本系统由 , , 和组成。
:
package fic;
public enum Lamp {
//前进 ,左拐 ,右拐
S2N("N2S","S2W",false), S2W("N2E","E2W",false), S2E(null,null,true),
E2W("W2E","E2S",false), E2S("W2N","S2N",false), E2N(null,null,true),
N2S(null,null,false) , N2E(null,null,false), N2W(null,null,true),
W2E(null,null,false) , W2N(null,null,false), W2S(null,null,true);
String opposite;
String next;
boolean lighted;
//构造函数:初始化当前灯
private Lamp(String opposite,String next,boolean lighted){
site = opposite;
= next;
ted = lighted;
}
//返回当前灯的状态
public boolean isLighted(){return lighted;}
public void light(){
ted = true;
if(opposite != null){
eOf(opposite)。light();
}
tln(name() + "is Green. Soon there will be cars crossed the street at six deractions.");
}
public Lamp blackout(){
//关闭当前灯 : 设为false
ted = false;
Lamp nextLamp = null;
if(opposite != null){eOf(opposite)。blackout();}
//检查下一个灯并启动它
if(next != null){
nextLamp = eOf(next);
tln(name() + " to the " + next + " 's light is Green.");
t();
}
return nextLamp;
}
}
package fic;
import utors;
import Unit;
public class LampController {
private Lamp currentLamp;
public LampController(){
currentLamp = Lamp.S2N;
t();
//启动一个线程 : 每十秒将当前灯设置为红
cheduledThreadPool(1)。scheduleAtFixedRate(
new Runnable() {
public void run() {
currentLamp = kout();
}
},
10,
10,
NDS
);
}
}
package fic;
import ;
import yList;
import om;
import utors;
import Unit;
public class Road {
private String name;
private List
public Road(String name){
= name;
//模拟车辆不断随机上路的过程
ingleThreadExecutor()。execute(new Runnable() {
public void run() {
for(int i = 0 ; i < 1000 ;i++){
try {
p((new Random()。nextInt(10) + 1) * 1000);
} catch (InterruptedException e) {
tStackTrace();
}
( + "_" + i);
}
}
});
//每隔一秒检查对应的'灯是否为绿,如果是 ,则放行一辆车,具体操作为从vehicles集合中移除第一辆车。
cheduledThreadPool(1)。scheduleAtFixedRate(
new Runnable() {
public void run() {
if(() > 0){
if(eOf()。isLighted()){
tln(ve(0) + " is traversing");
}
}
}
},
1,
1,
NDS);
}
}
最后在Main方法中启动系统:public static void main(String[] args) {
String[] deractions = {"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"};
//模拟十二条方向的路线
for(int i = 0 ; i < th; i++){
new Road(deractions[i]);
}
//启动交通灯控制器
new LampController();
}