【发布时间】:2022-01-23 08:23:06
【问题描述】:
我正在安排线程池上的任务。我的要求是每个任务最多将相同的逻辑迭代 4 次,但在每次迭代之前,如果满足某些条件,我想终止该任务。
调度任务->
ScheduledExecutorService scheduledExecutorService;
// Submitting the task to the thread pool
scheduledExecutorService.scheduleAtFixedRate(new Task(payload),
AppConstants.INITIAL_DELAY_IN_MINUTES,
AppConstants.INTERVAL_BETWEEN_DELIVERY_IN_MINUTES,
TimeUnit.MINUTES);
Task类的run方法(实现Runnable)->
@Override
public void run() {
if (shouldTaskTerminate())
terminateTask("Counter reached it's upper bound for " + payload.getEventId());
// Handling the task if the above condition is not satisfied
}
private void terminateTask(String taskTerminationReason) {
log.info(" {}. So, cancelling the task of {} ", taskTerminationReason, Thread.currentThread().getId());
throw new RuntimeException("Task lifecycle completed.");
}
正如上面代码sn-p中提到的,我抛出一个异常来终止任务。我通过参考JavaDoc here了解了这种终止任务的方式。
这是终止任务的正确方法吗?我还知道,当我将任务提交到线程池时,另一种终止任务的方法是取消未来对象。但是,就我而言,我想在 Task 类(即 Runnable 实现者)中终止它,因为 Task 类中定义的变量/数据库查询决定了未来的运行。
【问题讨论】:
标签: java multithreading