这是代码部分,LampController.java中的定时器好像都没有被执行
import java.util.*;
import java.util.concurrent.*;
class Traffic
{
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[i]);
}
new LampController();
}
}
class Road {
private String name=null;
List<String> vehicles=new ArrayList<String>();
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);//随机休眠时间0~9秒;
} catch (Exception e) {
}
vehicles.add(Road.this.name+"_"+i);
}
}
});
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable(){
public void run(){
if(vehicles.size()>0){
boolean lighted=Lamp.valueOf(Road.this.name).isLigthed();
if(lighted)
System.out.println(vehicles.remove(0)+"过去了");
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
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",false),E2N("null","null",false),N2W("null","null",false),W2S("null","null",false);
private String opposite;
private String next;
private boolean ligthed;
private Lamp(String opposite,String next,boolean state){
this.opposite=opposite;
this.next=next;
this.ligthed=state;
}
private Lamp(){}
public boolean isLigthed(){
return ligthed;
}
public void ligth(){
this.ligthed=true;
if(opposite!=null)
{
Lamp.valueOf(opposite).ligth();
}
System.out.println(name()+"变绿灯了");
}
public Lamp blockOut(){
System.out.println("红灯");
if(opposite!=null)
{
Lamp.valueOf(opposite).blockOut();
}
this.ligthed=false;
Lamp nextLamp=null;
if(next!=null)
{
nextLamp=Lamp.valueOf(next);
nextLamp.ligth();
}
return nextLamp;
}
}
class LampController {
private Lamp currentLamp;
public LampController(){
currentLamp=Lamp.S2N;
currentLamp.ligth();
System.out.println("切换1");
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable(){
public void run(){
System.out.println("切换");
currentLamp=currentLamp.blockOut();
}
},
2,
2,
TimeUnit.SECONDS);
}
} |