本帖最后由 姜胜凯 于 2014-1-12 19:41 编辑
package com.itheima.traffic;
import java.util.ArrayList;
import java.util.List;
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> cars = 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 x=1;x<500;x++){
try {
Thread.sleep((new Random().nextInt(10)+1)*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cars.add(Road.this.name+"_第"+x+"汽车");
// System.out.println(Road.this.name+"_第"+x+"汽车");
}
}
});
ScheduledExecutorService timer =Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable(){
public void run(){
**** if(cars.size()>0){
boolean lamp2green=Lamp.valueOf(Road.this.name).isGreen();
if(lamp2green)
System.out.println(cars.remove(0)+"开过去了");
}
}
},
1,
1,
TimeUnit.SECONDS);
}
}
****处用于判断路上是否有车的语句是否可以换成(cars!=null)。
集合cars (cars!=null)和(cars>0)的区别~
换上就会出错,求高手解答下为什么。 |