1、execute方法,子线程中有异常会抛出异常;
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
for (int i=0;i<10;i++) {
threadPoolExecutor.execute(()->doTask("execute"));
}
threadPoolExecutor.shutdown();
}
private static void doTask(String string)throws RuntimeException {
String str = "ThreadName:"+ Thread.currentThread().getName()+"执行方式:"+string;
System.out.println(str);
List list = null;
System.out.println(list.size());
}
2、submit方法,子线程中有异常不会抛出,需要使用future.get()方法获取异常信息;
public class ThreadPools { public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); for (int i=0;i<10;i++) { Future future = threadPoolExecutor.submit(()->doTask("submit")); try { future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } threadPoolExecutor.shutdown(); } private static void doTask(String string)throws RuntimeException { String str = "ThreadName:"+ Thread.currentThread().getName()+"执行方式:"+string; System.out.println(str); List list = null; System.out.println(list.size()); /* try { System.out.println(list.size()); }catch (Exception e) { System.out.println(e.getMessage()); } */ } }
但是如果子线程中异常在子线程中被捕获到没有抛出,future.get()方法不会获取到异常信息;
public class ThreadPools {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
for (int i=0;i<10;i++) {
Future future = threadPoolExecutor.submit(()->doTask("submit"));
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
threadPoolExecutor.shutdown();
}
private static void doTask(String string)throws RuntimeException {
String str = "ThreadName:"+ Thread.currentThread().getName()+"执行方式:"+string;
System.out.println(str);
List list = null;
try {
System.out.println(list.size());
}catch (Exception e) {
System.out.println(e.getMessage());
}
}