黑马程序员技术交流社区
标题:
求助关于交通灯系统视频
[打印本页]
作者:
翟友伟
时间:
2012-3-30 16:35
标题:
求助关于交通灯系统视频
按照视频上的代码来打。。 不知道哪里有问题
最后输入结果, 当前绿灯转换不过来, 总是固定停在一个 上 ,
提示为 :
S2N为绿灯 ------------一开始的没问题
N2S为绿灯
-------------------------
----------------------
--------------
-------------------------
----------------------
--------------
绿灯从"S2N"----切换为S2W
以后无论继续运行 一直显示 “绿灯从"S2N"----切换为S2W ”
贴上代码,,,哪位同学帮我看看 哪里出问题了。。。谢谢l了
Lamp类
package com.itcast;
public enum Lamp {
S2N("N2S","S2W",false),S2W("N2S","S2W",false),
E2W("W2E","E2S",false),E2S("W2N","S2N",false),
S2E(null,null,true),E2N(null,null,true),
N2W(null,null,true),W2S(null,null,true),
N2S(null,null,false),N2E(null,null,false),
W2E(null,null,false),W2N(null,null,false);
private String opposite;
private boolean lighted;
private String next;
private Lamp(String opposite,String next,boolean lighted)
{
this.opposite=opposite;
this.next=next;
this.lighted=lighted;
}
public void light()
{
this.lighted=true;
if(opposite!=null)
{
Lamp.valueOf(opposite).light();
}
System.out.println(name()+"绿了");
}
public boolean isLighted()
{
return lighted;
}
public Lamp blackOut()
{
this.lighted=false;
if(opposite!=null)
{
Lamp lampOpposite =Lamp.valueOf(opposite);
lampOpposite.blackOut();
}
Lamp nextLamp =null;
if(next!=null)
{
nextLamp=Lamp.valueOf(next);
System.out.println("绿灯从"+name()+"----切换为"+next);
nextLamp.light();
}
return nextLamp;
}
}
复制代码
LampController类
public class LampController
{
private Lamp currentLamp ;
public LampController()
{
currentLamp =Lamp.S2N;
currentLamp.light();
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable()
{
public void run()
{
currentLamp = currentLamp.blackOut();
}
},
6,6,TimeUnit.SECONDS);
}
}
复制代码
Road类
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);
}
}
复制代码
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[i]);
}
new LampController();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2