本帖最后由 黑马11期李项京 于 2012-6-3 23:32 编辑
经过本人试验:Executors.newSingleThreadScheduledExecutor()和
Executors.newScheduledThreadPool(1);产生效果其实是一样的,可以互相替换,那张老师为什么不用同一个线程方法呢?
张老师的代码:- //模拟车辆不断随机上路的过程
- 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);
-
- }
复制代码 |