线程池中 submit() 和 execute() 方法有什么区别?
答:
submit() 和 execute()都可以开启线程执行池中的任务。但是 submit()可以提交指定的任务去执行并且返回Future对象,即执行的结果。
区别:
- 接收的参数不一样
public class MainTest {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("execute");
}
});
Future<?> submit = pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("submit");
}
});
//等任务执行完毕会打印null
System.out.println(submit.get());
FutureTask<Integer> submit2 = (FutureTask<Integer>) pool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("submit_2");
return 2;
}
});
System.out.println("result=" + submit2.get());
}
}
- 返回值不一样
- submit有Future < T > 类型的返回值,而execute没有。
- submit方便Exception处理
- 感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。
public class MainTest {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(10);
Future submit = pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("submit");
System.out.println(0/0);
}
});
try {
System.out.println("result=" + submit.get());
}catch (Exception e){
System.out.println(e);
}
}
}