请问我这的结果为什么会是这样,老师的都是输出的是两行 6个方向的汽车穿过,我这只是一行,切方向顺序也不一样。我检查了代码是对的啊,为什么结果不一样呢!public class Road {
private List<String> vechicles = new ArrayList<String>();
private String name=null;
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 {
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
vechicles.add(Road.this.name + "_" + i);
}
}
});
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
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
);
}
}
public enum Lamp {
//"S2N","S2W","E2W","E2S"
//"N2S","N2E","W2E","W2N"
//"S2E","E2N","N2W","W2S"
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 boolean lighted;
private String opposite;
private String next;
private Lamp(String opposite,String next,boolean lighted){
this.opposite=opposite;
this.next=next;
this.lighted=lighted;
}
private Lamp(){
}
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 下面总共可以有六个方向看到汽车穿梭");
}
}
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;
}
}
public class lampController {
private Lamp currentLamp;
public lampController() {
this.currentLamp = Lamp.S2N;
this.currentLamp.light();
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
System.out.println("--来了--");
currentLamp=currentLamp.blackOut();
}
},
10,
10,
TimeUnit.SECONDS);
}
}
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);
}
new lampController();
}
}
请指教!!!
|
|