我是Java编程的新手,但我陷入了一个问题。我正在使用Spring TaskExecutor接口(interface)进行线程池管理。我必须并行地从不同的源(Http,Files,Databse)中提取内容,因此我为此使用了TaskExecutor
现在,我希望所有线程执行完毕后,应该指示TaskExecutor,如果它们在4秒钟内还没有完成执行,则应该终止任务。所以我陷入了这个问题。我尝试在将来使用可调用接口(interface),但这会导致任务同步执行,但我需要异步。请帮帮我。

最佳答案

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

 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;
    }
}

}

10-04 11:20