本帖最后由 张学林 于 2013-3-5 12:05 编辑
- 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(){//通过blackOut方法获取下一个线路的绿灯
- currentLamp = currentLamp.blackOut();
- }
- },
- 3,
- 3,
- TimeUnit.SECONDS);
- }
- }
复制代码 因为初始绿灯为S2N,当S2N.blackOut()时- public Lamp blackOut(){
- this.lighted = false;
- if(opposite != null){
- Lamp.valueOf(opposite).blackOut();
-
- }
- //
- // Lamp nextLamp = Lamp.valueOf(next);
- //
- // if(next != null){
- // System.out.println("绿灯从"+ name() + "----------->切换为"+ next);
- // nextLamp.light();
- // }
-
- Lamp nextLamp = null;
- if(next != null){
- System.out.println("绿灯从"+ name() + "----------->切换为"+ next);
- nextLamp = Lamp.valueOf(next);
- nextLamp.light();
- }
- return nextLamp;
- }
复制代码 blackOut方法执行了S2N.lighted = false;由于(opposite=N2S)不等于空
又执行了N2S.blackOut() N2S.lighted = false; 此时opposite和next都为null以至于后面的
Lamp nextLamp = Lamp.valueOf(next) ;会出空指针异常 |