gpt4 book ai didi

java - ThreadPoolTask​​Executor 关闭/重新运行问题

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:58 26 4
gpt4 key购买 nike

我正在尝试使用 Spring 的“ThreadPoolTask​​Executor”来实现多线程连续任务执行。

这是我使用它的类(class):

@Component
public class AsyncWorker implements Worker {
public int threadCount = 5;
private ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

@Async
public void doWork(Runnable runnable){
executor.initialize();
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setCorePoolSize(threadCount);
executor.setMaxPoolSize(threadCount);
executor.setQueueCapacity(0);
executor.setThreadGroupName("A");

for (int i=0;i<5;i++) {
executor.submit(runnable);
}
System.out.println("Active threads: " +executor.getActiveCount());
}

@Async
public void StopTasks(){
executor.shutdown();
}

用法:

@Controller
@RequestMapping("api/test")
public class SendController {

ThreadPoolExecutor executor = new ErrorReportingThreadPoolExecutor(5);

@Autowired AsyncWorker worker;
boolean IsRunning = true;

@RequestMapping(value = "/start_new", method = RequestMethod.POST)
public Callable<String> StartNewTask(@RequestBody LaunchSend sendobj) throws IOException, InterruptedException {

// System.out.println(sendobj.getThreadsCount());
Runnable runnable = () -> {
while(IsRunning) {
MyVoid();
}
};

worker.doWork(runnable);

return () -> "Callable result";
}

@RequestMapping(value = "/stop", method = RequestMethod.GET)
public Callable<String> StopTasks() {
IsRunning =false;
if(SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
worker.StopTasks();
return () -> "Callable result good";
}
else { return () -> "Callable result bad";}
}
}

主要问题是:

当我第一次发送启动请求时 - 一切正常(除非我没有看到组名称的更改(executor.setThreadGroupName("A")))。

但是,在我发送停止请求并再次发送启动请求后 - 执行程序不会启动任务。它是这样的:

ThreadPoolTaskExecutor-4 Global iteration # 4
ThreadPoolTaskExecutor-2 Global iteration # 5
ThreadPoolTaskExecutor-5 Global iteration # 3
ThreadPoolTaskExecutor-3 Global iteration # 2
Active threads: 5
ThreadPoolTaskExecutor-1 Global iteration # 1
ThreadPoolTaskExecutor-2 Global iteration # 9
ThreadPoolTaskExecutor-3 Global iteration # 9
ThreadPoolTaskExecutor-5 Global iteration # 9
ThreadPoolTaskExecutor-4 Global iteration # 9
ThreadPoolTaskExecutor-1 Global iteration # 10
Active threads: 1

仅显示“Activity 线程:1”。可能会出现什么问题?

顺便说一句,将来,我想为它创建的 ThreadGroup 设置自定义名称(从 POST 请求/Spring Security 上下文传输的参数),然后能够使用某个组名称终止所有线程(组名称将是启动线程的用户的 Spring Security 用户名。)这可能吗?

最佳答案

一旦任务完成工作,它们就不再存在,您需要将它们重新提交给调度程序才能让它们再次运行。它们不会无限期地留在执行器内。

关于java - ThreadPoolTask​​Executor 关闭/重新运行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436946/

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