gpt4 book ai didi

java - Spring 任务执行器 :How to get notifed when all task complete execution and also if they dont in some time slot

转载 作者:搜寻专家 更新时间:2023-11-01 03:44:12 27 4
gpt4 key购买 nike

我是 Java 编程的新手,但遇到了一个问题。我正在使用 Spring TaskExecutor 接口(interface)进行线程池管理。我必须并行地从不同来源(Http、文件、数据库)提取内容,因此我为此使用了 TaskExecutor。现在我希望一旦所有线程都完成执行,它应该指示 TaskExecutor,如果它们没有在 4 秒内完成执行,则任务应该被终止。所以我被这个问题困住了。我尝试将可调用接口(interface)与 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;
}
}

}

关于java - Spring 任务执行器 :How to get notifed when all task complete execution and also if they dont in some time slot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6529883/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com