為了方便廣大程序猿交流和學習,下面小編準備了關於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();
}