黑马程序员技术交流社区
标题:
找错误代码果真是件痛苦的事
[打印本页]
作者:
陌路行者
时间:
2013-7-23 19:53
标题:
找错误代码果真是件痛苦的事
本帖最后由 杨兴庭 于 2013-7-28 22:50 编辑
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Road {
private List<String> vechicles = new ArrayList<String>();
private String name;
Road(String name){
this.name = name;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
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(){
Lamp currentLamp = Lamp.valueOf(Road.this.name);
if(currentLamp.isLighted()){
System.out.println(vechicles.remove(0)+" is traversing.....!");
}
}
},
1,
1,
TimeUnit.SECONDS
);
}
}
复制代码
public 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,true),E2N(null,null,true),N2W(null,null,true),W2S(null,null,true);
private Lamp(String opposite,String next,boolean lighted){
this.opposite = opposite;
this.next = next;
this.lighted = lighted;
}
private boolean lighted;
private String opposite;
private String next;
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 一共有6个方向能看到汽车通过");
}
public Lamp balckOut(){
this.lighted = false;
if(opposite!=null){
Lamp.valueOf(opposite).balckOut();
}
Lamp nextLamp = null;
if(next!=null){
nextLamp = Lamp.valueOf(next);
System.out.println("绿灯从"+name()+" 切换为------>"+next);
nextLamp.light();
}
return nextLamp;
}
}
复制代码
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LampController {
private Lamp currentLamp;
public LampController(){
currentLamp = currentLamp.S2N;
currentLamp.light();
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
currentLamp = currentLamp.balckOut();
}
},
10,
10,
TimeUnit.SECONDS
);
}
}
复制代码
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
String[] directions = {"S2N","S2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"};
for(int i=0;i<directions.length;i++){
new Road(directions[i]);
}
new LampController();
}
}
复制代码
QQ图片20130723195448.jpg
(96.97 KB, 下载次数: 0)
下载附件
2013-7-23 19:55 上传
作者:
yinjiek
时间:
2013-7-23 20:05
多添加注释;在road()中添加System.out.print("!")输出语句看哪句没有执行到;
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2