首頁  >  文章  >  Java  >  Java中Runnable與Callable的比較

Java中Runnable與Callable的比較

PHPz
PHPz轉載
2023-04-21 21:58:151378瀏覽

1、相同點

兩者都是介面

兩者都需要呼叫Thread.start啟動執行緒

2 、不同點

callable的核心是call()方法,允許回傳值,runnable的核心是run()方法,沒有回傳值

call()方法可以拋出異常,但是run()方法不行

callable和runnable都可以套用到executors,thread類別只支援runnable

3、實例

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;
}

以上是Java中Runnable與Callable的比較的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除