本帖最后由 谢军 于 2013-3-9 16:07 编辑
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> car=new ArrayList<String>();//张老师说用前面用list而不用ArrayList的原因是要面向接口编程,
// 在交通灯里有具体体现吗?还是只是预留接口为了以后的维护之便
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();
}
car.add(Road.this.name+" "+i);
}
}
});
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable(){
public void run(){
if(car.size()>0){
boolean lighted=Lamp.valueOf(Road.this.name).isLighted();
if(lighted){
System.out.println(car.remove(0)+"is traversing !");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
|