Spring TaskExecutor:如何在所有任务完成执行时以及在某个时间段内未完成时得到通知



我是java编程的新手,遇到了一个问题。我使用Spring TaskExecutor接口进行线程池管理。我必须并行地从不同的源(Http、Files、Databse)提取内容,所以我使用了TaskExecutor。现在,我希望一旦所有线程都完成了执行,它应该指示TaskExecutor,如果它们在4秒内没有完成执行,那么任务应该终止。所以我陷入了这个问题。我尝试使用future的可调用接口,但这会导致任务同步执行,但我需要异步。请帮帮我。

您还可以在任务创建后创建一个循环并检查超时:

 ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
taskExecutor.execute(new PrintTask("YOUR TASK ONE"));
taskExecutor.execute(new PrintTask("YOUR TASK TWO"));
double timeOutMs = 3000.0 ; // 3 seconds of maximum duration
double startTime = System.currentTimeMillis() ;
//check active thread, if zero then shut down the thread pool
for (;;) {
    int count = taskExecutor.getActiveCount();
    System.out.println("Active Threads : " + count);
                if (System.currentTimeMillis() - startTime > timeOutMs) {
                    // Do something : its to late, cancel the tasks !
                } 
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if (count == 0) {
        taskExecutor.shutdown();
        break;
    }
}
}

使用一个注释为@Async的方法,使其在单独的进程中运行。让它循环并跟踪自开始执行以来的秒数。如果超过4,则退出循环,线程将退出。请注意,@Async方法需要与生成它的方法位于不同的类中。

最新更新