任务拆分成子任务,并且等到所有子任务完成后通知方案
方案1
使用 CountDownLatch
public class SplitTaskScheduler {
private ExecutorService executor;
private CountDownLatch latch;
@Setter
private Runnable callback;
public SplitTaskScheduler(ExecutorService executor, CountDownLatch latch) {
this.executor = executor;
this.latch = latch;
}
public void start() {
executor.execute(() -> {
try {
latch.await();
log.info("{} all tasks execute finished", Thread.currentThread().getName());
if (callback!=null){
callback.run();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("await all task error", e);
}
});
}
public void submit(List<Runnable> list){
for (Runnable runnable : list) {
executor.submit(()->{
try {
runnable.run();
}finally {
latch.countDown();
}
});
}
}
public void shutdown(){
executor.shutdown();
}
public static void main(String[] args) {
int cnt = 5;
SplitTaskScheduler scheduler = new SplitTaskScheduler(Executors.newFixedThreadPool(4),new CountDownLatch(cnt));
scheduler.setCallback(() -> log.info("all tasks runs.."));
scheduler.start();
List<Runnable> list = new ArrayList<>();
for (int i = 0; i < cnt; i++) {
Runnable r = () -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
int i1 = random.nextInt(5);
log.info("{} execute task sleep: {}", Thread.currentThread().getName(), i1);
try {
TimeUnit.SECONDS.sleep(i1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
log.info("{} execute task finished", Thread.currentThread().getName());
};
list.add(r);
}
scheduler.submit(list);
scheduler.shutdown();
}
}
方案2-使用CompletableFuture
定义任务 Task
public interface Task {
CompletableFuture<Void> execute();
}
实现
@Slf4j
public class SubTask implements Task {
private String name;
public SubTask(String name) {
this.name = name;
}
@Override
public CompletableFuture<Void> execute() {
return CompletableFuture.runAsync(() -> {
Random random = new Random(10);
int i = random.nextInt(5) + 1;
log.info("{} run task: {}, sleep: {}", Thread.currentThread().getName(), name, i);
try {
if (name.equals("task3")) {
TimeUnit.SECONDS.sleep(1);
log.info("{} run task: {}, sleep 1 sec error", Thread.currentThread().getName(), name);
throw new RuntimeException("异常啦");
}
TimeUnit.SECONDS.sleep(i);
} catch (InterruptedException e) {
log.info("interrupt: {}", name, e);
}
log.info("{} run task finished: {}", Thread.currentThread().getName(), name);
});
}
}
任务调试器
@Slf4j
public class ScheduleManager {
public static void schedule(List<Task> tasks, Runnable callback){
List<CompletableFuture<Void>> futures = tasks.stream().map(Task::execute).toList();
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.handle((result,throwable) -> {
//只要有其中一个异常,就会执行
if (throwable!=null){
log.info("one of task is error {}", throwable.getMessage());
for (CompletableFuture<Void> future : futures) {
future.cancel(true);
}
return "有异常啦";
}
return null;
})
.thenRun(callback);
}
}
测试
List<Task> list = new ArrayList<>(){{
add(new SubTask("task1"));
add(new SubTask("task2"));
add(new SubTask("task3"));
add(new SubTask("task4"));
}};
ScheduleManager.schedule(list,()->{
log.info("all task execute");
});
TimeUnit.SECONDS.sleep(20);