本帖最后由 yuchunfeng1221 于 2013-10-16 15:30 编辑
交通灯面试题中第一个就是异步随机生成按照各个路线行驶的车辆 我想问问这个异步体现在哪里呢?
- 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);
-
- }
- }
复制代码 |