我有两个任务-任务A和任务B。任务A应该首先执行,当任务完成时,我想启动我的周期性任务B,它一直在做一个任务,直到它成功。我如何在java中实现这一点?我关注的是计划的执行服务,但这些服务似乎更多地基于时间而不是任务的状态。
发布于 2011-10-15 12:51:36
这里有一种方法:
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);
}
}
}https://stackoverflow.com/questions/7775622
复制相似问题