Home  >  Article  >  Java  >  Comparison of Runnable and Callable in Java

Comparison of Runnable and Callable in Java

PHPz
PHPzforward
2023-04-21 21:58:151426browse

1. Similarities

Both are interfaces

Both need to call Thread.start to start the thread

2 , Differences

The core of callable is the call() method, which allows return values. The core of runnable is the run() method, which has no return value.

The call() method can throw Exception, but the run() method does not work

Both callable and runnable can be applied to executors, the thread class only supports runnable

3, instance

Runnable and Callable interface definition

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

The above is the detailed content of Comparison of Runnable and Callable in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete