通过代码示例了解submit与execute的区别
(1)可以接受的任务类型
submit:
execute:
可以看出:
execute只能接受Runnable类型的任务
submit不管是Runnable还是Callable类型的任务都可以接受,但是Runnable返回值均为void,所以使用Future的get()获得的还是null
(2)返回值
由Callable和Runnable的区别可知:
execute没有返回值
submit有返回值,所以需要返回值的时候必须使用submit
(3)异常
1.execute中抛出异常
execute中的是Runnable接口的实现,所以只能使用try、catch来捕获CheckedException,通过实现UncaughtExceptionHande接口处理UncheckedException
即和普通线程的处理方式完全一致
2.submit中抛出异常
不管提交的是Runnable还是Callable类型的任务,如果不对返回值Future调用get()方法,都会吃掉异常
先来看下Callable定义
public interface Callable<V> {
V call() throws Exception;
}
其中的call能够抛出Exception异常,所以不管是CheckedException还是UncheckedException,直接抛出即可
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; } }
结果为:
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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)