public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newScheduledThreadPool(2);
        System.out.println("begin");
        for (int a = 0; a < 10; a++) {
            System.out.println(a);
            final int count = a;
            service.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+": "+count);
                }
            }, 2,2, TimeUnit.SECONDS);
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }        service.shutdown();
        System.out.println("stop");
    }运行结果:
begin
0
1
2
3
4
5
6
7
8
9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
pool-1-thread-1: 0
pool-1-thread-2: 1
pool-1-thread-1: 2
pool-1-thread-2: 3
pool-1-thread-1: 4
pool-1-thread-2: 5
pool-1-thread-1: 6
pool-1-thread-2: 7
pool-1-thread-1: 8
pool-1-thread-2: 9
stop
为什么线程内部print了 0-9两次循环?
为什么a只打印一次循环?

解决方案 »

  1.   

    for循环是main线程运行的。我认为第二次调度的时候会打印9,或者不打印。说实话我对这个程序怎么执行的不太清楚
      

  2.   

    你查查scheduleAtFixedRate这个方法的参数就明白了,scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnitunit),线程会在initialDelay这个时间后执行,在initialDelay+period时间后再次执行,你的代码为什么会执行两次,我的理解是,进入for循环后,调用scheduleAtFixedRate这个方法线程开始执行,打印一次,而在这次循环还没结束,就到了initialDelay+period这个时间点,所以又执行了一次,当你把period这个时间调大后,打印的循环就会变成一次了!