我有一个执行器服务,我提交多个线程做一些工作,现在我想取消/中断一些线程的执行,让我知道我怎么能这样做?
例如: - 下面是我的Thread类,它在无限次间隔后打印线程名称。
public class MyThread implements Runnable {
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
try {
System.out.println("Thread "+ name + " is running");
sleep(500);
}catch (InterruptedException e){
System.out.println("got the interrupted signal");
e.printStackTrace();
}
}
}
现在我通过给它们命名来创建多个线程,以便稍后我可以中断该特定线程并停止执行。
现在在我的Test类中,我正在创建4个线程,并希望停止执行名为 amit 和 k 的2个线程。
public class ThreadTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
MyThread amit = new MyThread("amit");
MyThread k = new MyThread("k");
MyThread blr = new MyThread("blr");
MyThread india = new MyThread("india");
executorService.submit(amit);
executorService.submit(k);
executorService.submit(blr);
executorService.submit(india);
// now i want to stop the execution of thread Named "amit" and "k".
}
}
让我知道我该怎么做?
答案 0 :(得分:10)
您的MyThread
实际上并未在具有这些名称的线程上运行。他们没有直接作为线程运行,而是在ExecutorService
的线程上运行。
因此,您需要保留名称到Future
的映射,然后在需要时取消将来。
Map<String, Future<?>> map = new HashMap<>();
map.put("amit", executorService.submit(amit));
map.put("k", executorService.submit(k));
// ... etc
然后,取消amit
:
map.get("amit").cancel(true);
当然,您可以简单地保留显式变量:
Future<?> amitFuture = executorService.submit(amit);
amitFuture.cancel(true);
但如果你有很多变数,这可能会很笨拙。