区别:
- submit(Callable<T> task)、submit(Runnable task, T result)、submit(Runnable task)归属于ExecutorService接口。
- execute(Runnable command)归属于Executor接口。ExecutorService继承了Executor。
- submit()有返回值。
- execute没有返回值。
public class ThreadPoolTest {
private String taskName;
public ThreadPoolTest(String taskName) {
this.taskName = taskName;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("execute任务执行中");
}
});
System.out.println("----分界线----");
Future<String> future = executorService.submit(() -> {
System.out.println("submit任务执行中");
return "submit任务完成,这是执行结果";
});
try {
//如果future.get()返回null,任务完成
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
System.out.println("任务失败原因:" + e.getCause().getMessage());
}
executorService.shutdown();
}
}
//输出:
----分界线----
execute任务执行中
submit任务执行中
submit任务完成,这是执行结果
- submit()方便做异常处理。通过Future.get()可捕获异常。
public class ThreadPoolTest implements Runnable {
private String taskName;
public ThreadPoolTest(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
throw new RuntimeException("此处" + this.taskName + "抛出异常。");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new ThreadPoolTest("task1"));
System.out.println("----分界线----");
Future<?> future = executorService.submit(new ThreadPoolTest("task2"));
try {
future.get();//如果future.get()返回null,任务完成
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
System.out.println("任务失败原因:" + e.getCause().getMessage());
}
executorService.shutdown();
}
}