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

Comparison of Runnable and Callable in Java

PHPz
Release: 2023-04-21 21:58:15
forward
1448 people have browsed it

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();
}
Copy after login
@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;
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template