本帖最后由 夏晓彤 于 2013-3-24 20:50 编辑
问题:当创建 Road对象时,构造函数中还有线程还没执行完呢,12个对象就创立了,根本没走线程代码,然后执行 new LampController();然后才执行Road类中的线程,总之线程在构造函数中就看不懂了,不知道怎么执行顺序了,我认为new Road(directions[0]);要把构造函数里的所有代码执行完才可以new Road(directions[1]),Road类的构造方法中的两个线程不懂怎么执行的
package com.isoftstone.interview.traffic;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
/*产生12个方向的路线*/
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();
}
}
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);
}
}
|