The difference between the Runnable and Callable interfaces in Java

在设计Java中的并发线程时使用Runnable和Callable接口有什么区别,为什么你会选择一个呢?


See explanation here.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.


What are the differences in the applications of Runnable and Callable . Is the difference only with the return parameter present in Callable ?

Basically, yes. See the answers to this question. And the javadoc for Callable .

What is the need of having both if Callable can do all that Runnable does?

Because the Runnable interface cannot do everything that Callable does!

Runnable has been around since Java 1.0, but Callable was only introduced in Java 1.5 ... to handle use-cases that Runnable does not support. In theory, the Java team could have changed the signature of the Runnable.run() method, but this would have broken binary compatiblity with pre-1.5 code, requiring recoding when migrating old Java code to newer JVMs. That is a BIG NO-NO. Java strives to be backwards compatible ... and that's been one of Java's biggest selling points for business computing.

And, obviously, there are use-cases where a task doesn't need to return a result or throw a checked exception. For those use-cases, using Runnable is more concise than using Callable<Void> and returning a dummy ( null ) value from the call() method.


  • A Callable needs to implement call() method while a Runnable needs to implement run() method.
  • A Callable can return a value but a Runnable cannot.
  • A Callable can throw checked exception but a Runnable cannot.
  • A Callable can be used with ExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks) methods but a Runnable cannot be.

    public interface Runnable {
        void run();
    }
    
    public interface Callable<V> {
        V call() throws Exception;
    }
    
  • 链接地址: http://www.djcxy.com/p/16382.html

    上一篇: ExecutorService vs休闲线程Spawner

    下一篇: Java中Runnable和Callable接口的区别