首页 > 解决方案 > 如何在 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
}

标签: javaspringspring-boot

解决方案


您可能需要维护线程名称和 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。


推荐阅读