1、接收的参数不同
由以上图看出,execute()只能接受Runnable类型参数,而submit()函数还可以接受Callable类型参数;
2、有无返回值
submit()函数都有返回值Future,而execute()函数没有返回值;
3、submit()方便exception处理
submit()函数可以通过Future.get()函数可以判断任务是不是执行完成;
如果在task里会抛出checked或者unchecked exception,而又希望外面的调用者能够感知这些exception并做出及时的处理,那么就需要用到submit,通过捕获Future.get抛出的异常。
class RunnableTest implements Runnable{
private String taskName;
public RunnableTest(final String taskName){
this.taskName=taskName;
}
public void run(){
System.out.println("inside "+taskName);
throw new RuntimeException("exception from "+taskName);
}
}
public class submitVSexecute {
public static void main(String[] args) {
ExecutorService pool=Executors.newFixedThreadPool(2);
pool.execute(new RunnableTest("task1"));
Future task2 = pool.submit(new RunnableTest("task2"));
try{
if(task2.get()==null){
System.out.println("任务完成");
}
}catch(InterruptedException e){
}catch(ExecutionException e){
System.out.println(e.getCause().getMessage());
}
}
}