如何从它的一个线程关闭一个ExecutorService ?



我想停止整个ExecutorService,如果一个(特定的线程)的线程管理失败的异常。是否可以简单地从线程内调用ExecutorService#shutdown?

对于Executorservice,如果从线程(使用.get()方法)获得返回的数据失败,则会抛出ExecutionException。你有2种情况:传递Runnablesubmit方法,或者传递Callable,在这两种情况下,你都可以使用.get()方法在执行后从线程检索数据。

所以你可以在所有线程的执行中添加.get()方法,并在submit方法的调用中加入一个try catch块来处理ExecutionException

这个例子将解释这个想法:

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
static ExecutorService service = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
try {
// Callable
System.out.println(service.submit(() -> {
return "Hello";
}).get());
} catch (ExecutionException e) {
System.out.println(e.getMessage());
// shutDown the service : if you delete the next line , service will still
// working
service.shutdownNow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// Runnable
service.submit(() -> {
throw new IOException();
}).get();
} catch (ExecutionException e) {
System.out.println(e.getMessage());
// shutDown the service : if you delete the next line , service will still
// working
service.shutdownNow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最新更新