public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
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);//在实例化路线对象的时候,当将四个向右转弯的路线实例化之后,那四条路上的车是不是一直在通行,不用考虑路灯,
//然而为什么每次在运行程序的时候,都会是“S2N,N2S”着两条路线先执行,而不是那四条右转弯的车辆相同行呀,
//主函数的线程是按顺序执行的,按理说应该先创建完所有的路线,(此时那四条路线已经存在,并且lighted为true,
此时可以进行remove()方法了呀。)
//灯的控制器是在下面一行才创建的应该后执行,可是为什么每次执行的都是:N2S Lamp is green!下面将会有六个方向的车可以通行!
S2N Lamp is green!下面将会有六个方向的车可以通行!
}
new LampControl();//灯的控制器是怎么样控制路灯的变化的?是必须有它才能开启整个交通灯系统的运作吗?
}
}
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Road {
private List<String> vehicles=new ArrayList<String>();
String name=null;
public Road( String name){
this.name=name;
ExecutorService pool=Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<1000;i++)
{
try {
Thread.sleep((new Random().nextInt(10)+1)*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vehicles.add(Road.this.name+"---"+i);
}
}
});
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
if(vehicles.size()>0){
boolean lighted=Lamp.valueOf(Road.this.name).isLighted();
// System.out.println(Road.this.name);
if(lighted)
{
//System.out.println(lighted);
System.out.println(vehicles.remove(0)//因为车辆集合由List创建的,根据List的特性,remove(0)表示的就是移除列表中的第一个元素,
//然后后面的元素向左移动(并且索引减 1),这样每次都移除的就是排队排在前面的车子,
//你可以想象,交通灯前的车子,肯定是按照顺序,离路口近的车先行驶过路口,然后后面的车子跟上,符合道道路现状.
// remove(0)表达的就是这个意思
+ "---is travaling!");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class LampControl {
private Lamp currentlamp;
public LampControl(){
currentlamp=Lamp.S2N;
currentlamp.light();
ScheduledExecutorService timer=Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
currentlamp= currentlamp.lightOut();
}
},
10,
10,
TimeUnit.SECONDS);
}
}
请明白人指点迷津,谢谢!!!
|
|