Java:计划任务

时间:2011-10-15 03:51:13

标签: java multithreading scheduled-tasks

我有2个任务 - 任务A和任务B.任务A应该首先执行并且在完成时,我想开始我的周期性任务B,它继续执行任务直到它成功。 我怎样才能在java中实现它?我正在查看预定的执行服务,但这些似乎是基于时间而不是任务状态。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

import java.util.concurrent.*;

public class ScheduledTasks {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
        FollowupTask followupTask = new FollowupTask(executorService);
        FirstTask firstTask = new FirstTask(followupTask, executorService);
        executorService.submit(firstTask);
    }

    static class FirstTask implements Runnable {
        private FollowupTask followup;
        private ScheduledExecutorService executorService;

        FirstTask(FollowupTask followup, ScheduledExecutorService executorService) {
            this.followup = followup;
            this.executorService = executorService;
        }

        @Override
        public void run() {
            System.out.println("First task: counting to 5");
            for (int i = 1; i <= 5; i++) {
                sleep(1000);
                System.out.println(i);
            }
            System.out.println("All done! Submitting followup task.");
            executorService.submit(followup);
        }
    }

    static class FollowupTask implements Runnable {
        private int invocationCount = 0;
        private ScheduledExecutorService executorService;

        public FollowupTask(ScheduledExecutorService executorService) {
            this.executorService = executorService;
        }

        @Override
        public void run() {
            invocationCount++;
            if (invocationCount == 1) {
                System.out.println("Followup task: resubmit while invocationCount < 20");
            }
            System.out.println("invocationCount = " + invocationCount);
            if (invocationCount < 20) {
                executorService.schedule(this, 250, TimeUnit.MILLISECONDS);
            } else {
                executorService.shutdown();
            }
        }
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new IllegalStateException("I shouldn't be interrupted!", e);
        }
    }
}