java - 如何在 Java 中中断/停止工作线程(不是当前线程)
问题描述
大家好
我想停止一个不是当前的工作线程
我不想这样
Thread. currentThread().interrupt()
因为它仅适用于同一方法块中的当前线程
我想用它的名字阻止任何线程
笔记:
这种方式行不通,因为我的线程不是当前线程,并且interrupt()
方法仅适用于我提到的当前线程
Set<Thread> setOfThread = Thread.getAllStackTraces().keySet();
//Iterate over set to find yours
for(Thread thread : setOfThread){
if(thread.getId()==yourThread.getId()){
thread.interrupt();
}
}
以下是我的代码
@Bean(name = "threadPoolExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("threadPoolExecutor-");
executor.initialize();
return executor;
}
和
@Async("threadPoolExecutor")
public void MyTask(){
System.out.println("Currently Executing thread name - " +
Thread.currentThread().getName());
System.out.println("User created with thread pool executor");
}
所以当我执行 MyTask() 它需要一个名字
我的问题是我想在 x 时间后按其名称停止此进程,并且仅当我请求 stop() 方法时,只要线程仍在工作
例如
@GetMapping(value="/stopThreadByName/{threadname}")
public String stop(@PathVariable("threadname") String name) {
//some code to stop the thread by its name
}
解决方案
您可能需要维护线程名称和 Task 的 Future 引用的映射。
public static Map<String, Future> futureMap = new HashMap<String, Future>();
@Async("threadPoolExecutor")
public Future<String> MyTask(String name){
...
Future<String> obj = new AsyncResult<String>("something");
futureMap.put(name, obj);
return obj;
}
futureMap.put(taskName, executor.submit(task));
当你调用 stop 时,
@GetMapping(value="/stopThreadByName/{threadname}")
public String stop(@PathVariable("threadname") String name) {
//some code to stop the thread by its name
Future taskNeedsToBeStop = futureMap.get("taskNeedsToBeStop");
taskNeedsToBeStop.cancel(true);
}
这里,
<T> Future<T> submit(Callable<T> task)
提交一个返回值的任务以供执行,并返回一个表示该任务待处理结果的 Future。Future 的 get 方法将在成功完成后返回任务的结果。
如果您想立即阻止等待任务,可以使用表单的构造result = exec.submit(aCallable).get();
boolean cancel(boolean mayInterruptIfRunning)
尝试取消此任务的执行。如果任务已完成、已被取消或由于某些其他原因无法取消,则此尝试将失败。如果成功,并且该任务在被调用时尚未启动,cancel
则该任务不应该运行。如果任务已经开始,则该mayInterruptIfRunning
参数确定是否应该中断执行该任务的线程以尝试停止该任务。
此方法返回后,后续调用isDone()
将始终返回 true。如果此方法返回 true,则后续调用isCancelled()
将始终返回 true。
推荐阅读
- python - 如何从 for 循环中创建一个全局变量
- postgresql - 如何在 PostgreSQL 中使用时间戳转换为日期表达式创建唯一的可延迟约束?
- python - 来自另一个模块类的 Python 导入方法
- java - java, spring boot 在运行时自动生成getter和setter
- sql - 使用 in (select ...) 子句进行查询优化
- javascript - 使用 Charts.js 从分组的 JSON 对象绘制多线图
- powershell - 有什么方法可以从 Powershell 命令行打开 Active Directory 用户和计算机中的用户属性?
- thymeleaf - 如何在无状态编程中从 UI 取消正在运行的查询
- swift - 仅使用 UITableView 更新 JSON 数组记录
- javascript - 有没有办法将 Google 文档分割成多个 PDF?