Wetts's blog

Stay Hungry, Stay Foolish.

0%

Java-API-ExecutorService的submit与execute区别

转自:http://blog.csdn.net/cpf2016/article/details/50150205

区别

可以接受的任务类型

  • execute只能接受Runnable类型的任务
  • submit不管是Runnable还是Callable类型的任务都可以接受,但是Runnable返回值均为void,所以使用Future的get()获得的还是null

返回值

由Callable和Runnable的区别可知:

  • execute没有返回值
  • submit有返回值,所以需要返回值的时候必须使用submit

异常

  • submit()能在返回的Future对象调用get()方法的时候再次抛出线程中的异常
  • execute()会交由线程的UncaughtExceptionHandler去处理。

execute中抛出异常

execute中的是Runnable接口的实现,所以只能使用try、catch来捕获CheckedException,通过实现UncaughtExceptionHande接口处理UncheckedException

即和普通线程的处理方式完全一致

submit中抛出异常

不管提交的是Runnable还是Callable类型的任务,如果不对返回值Future调用get()方法,都会吃掉异常

先来看下Callable定义

1
2
3
public interface Callable<V> {  
V call() throws Exception;
}

其中的call能够抛出Exception异常,所以不管是CheckedException还是UncheckedException,直接抛出即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadExceptionTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();

Future<Boolean> future = executor.submit(new CallableTask());
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

executor.shutdown();//必须不能忘,否则会一致卡在那里
}
}

class CallableTask implements Callable<Boolean>{
public Boolean call() throws Exception {
// InputStream in = new FileInputStream(new File("xx.pdf"));
int num = 3/0;
return false;
}

}

结果为:

1
2
3
4
5
6
7
8
9
10
11
12
java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero  
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at my.ThreadExceptionTest.main(ThreadExceptionTest.java:21)
Caused by: java.lang.ArithmeticException: / by zero
at my.CallableTask.call(ThreadExceptionTest.java:57)
at my.CallableTask.call(ThreadExceptionTest.java:1)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)