java中Runnable和Callable的区别
文章目錄
- 運行機制
- 返回值的不同
- Exception處理
java中Runnable和Callable的區別
在java的多線程開發中Runnable一直以來都是多線程的核心,而Callable是java1.5添加進來的一個增強版本。
本文我們會詳細探討Runnable和Callable的區別。
運行機制
首先看下Runnable和Callable的接口定義:
@FunctionalInterface public interface Runnable {/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see java.lang.Thread#run()*/public abstract void run(); } @FunctionalInterface public interface Callable<V> {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception; }Runnable需要實現run()方法,Callable需要實現call()方法。
我們都知道要自定義一個Thread有兩種方法,一是繼承Thread,而是實現Runnable接口,這是因為Thread本身就是一個Runnable的實現:
class Thread implements Runnable {/* Make sure registerNatives is the first thing <clinit> does. */private static native void registerNatives();static {registerNatives();}...所以Runnable可以通過Runnable和之前我們介紹的ExecutorService 來執行,而Callable則只能通過ExecutorService 來執行。
返回值的不同
根據上面兩個接口的定義,Runnable是不返還值的,而Callable可以返回值。
如果我們都通過ExecutorService來提交,看看有什么不同:
- 使用runnable
- 使用callable
雖然我們都返回了Future,但是runnable的情況下Future將不包含任何值。
Exception處理
Runnable的run()方法定義沒有拋出任何異常,所以任何的Checked Exception都需要在run()實現方法中自行處理。
Callable的Call()方法拋出了throws Exception,所以可以在call()方法的外部,捕捉到Checked Exception。我們看下Callable中異常的處理。
public void executeTaskWithException(){ExecutorService executorService = Executors.newSingleThreadExecutor();Future future = executorService.submit(()->{log.info("in callable!!!!");throw new CustomerException("a customer Exception");});try {Object object= future.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();e.getCause();}executorService.shutdown();}上面的例子中,我們在Callable中拋出了一個自定義的CustomerException。
這個異常會被包含在返回的Future中。當我們調用future.get()方法時,就會拋出ExecutionException,通過e.getCause(),就可以獲取到包含在里面的具體異常信息。
本文的例子可以參考https://github.com/ddean2009/learn-java-concurrency/tree/master/runnable-callable
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
更多教程請參考 flydean的博客
總結
以上是生活随笔為你收集整理的java中Runnable和Callable的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java并发中ExecutorServi
- 下一篇: java中ThreadLocal的使用