首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:计划任务

Java:计划任务
EN

Stack Overflow用户
提问于 2011-10-15 11:51:13
回答 1查看 1K关注 0票数 1

我有两个任务-任务A和任务B。任务A应该首先执行,当任务完成时,我想启动我的周期性任务B,它一直在做一个任务,直到它成功。我如何在java中实现这一点?我关注的是计划的执行服务,但这些服务似乎更多地基于时间而不是任务的状态。

EN

回答 1

Stack Overflow用户

发布于 2011-10-15 12:51:36

这里有一种方法:

代码语言:javascript
复制
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);
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7775622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档