首页 > 解决方案 > ScheduledExecutorService 执行与它下面的其他代码并行运行

问题描述

我是第一次使用 ScheduledExecutorService,但无法理解它的行为。我编写了一个简单的代码并假设它按顺序执行,但事实并非如此。

 public static void main(String[] args) throws InterruptedException {

    AtomicInteger runTimeCounter = new AtomicInteger(1);
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    int totalCountToRun = 4;
    int threadSleepTime = 5;
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (runTimeCounter.get() <= totalCountToRun) {

                try {
                    SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss z");
                    Date date = new Date(System.currentTimeMillis());
                    String time = formatter.format(date);
                    //create threaddump files in temp location
                    System.out.println("from task "+time);
                    //Increment the counter
                    runTimeCounter.getAndIncrement();
                } catch (Exception ex) {

                }
            } else {

                executorService.shutdown();
            }
        }
    }, 5, threadSleepTime, TimeUnit.SECONDS);

    for(int i=1;i<=4;i++ ){
        SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        //create threaddump files in temp location
        System.out.println("from for "+time);
        Thread.sleep(5000);

    }

}

它打印:

from for 22:17:27 IST
from task 22:17:27 IST
from task 22:17:32 IST
from for 22:17:32 IST
from task 22:17:37 IST
from for 22:17:37 IST

from task 22:17:42 IST
from for 22:17:42 IST

有人可以指导我这里到底发生了什么以及如何按顺序运行代码。

标签: javascheduledexecutorservice

解决方案


推荐阅读