Shall Callable be preferred over Runnable?

后端 未结 5 1731
小蘑菇
小蘑菇 2021-02-01 02:04

I have understood the difference between Runnable and Callable interface in Java. From Java 1.5 additional features has been added to Runnable

5条回答
  •  青春惊慌失措
    2021-02-01 02:51

    Callable and Runnable both is similar to each other and can use in implementing thread. In case of implementing Runnable you must implement run() method but in case of callable you must need to implement call() method, both method works in similar ways but callable call() method have more flexibility.There is some differences between them.

    Difference between Runnable and callable as below--

    1) The run() method of runnable returns void, means if you want your thread return something which you can use further then you have no choice with Runnable run() method. There is a solution 'Callable', If you want to return any thing in form of object then you should use Callable instead of Runnable. Callable interface have method 'call()' which returns Object.

    Method signature - Runnable->

    public void run(){}
    

    Callable->

    public Object call(){}
    

    2) In case of Runnable run() method if any checked exception arises then you must need to handled with try catch block, but in case of Callable call() method you can throw checked exception as below

     public Object call() throws Exception {}
    

    3) Runnable comes from legacy java 1.0 version, but callable came in Java 1.5 version with Executer framework.

    If you are familiar with Executers then you should use Callable instead of Runnable.

    Hope you understand.

提交回复
热议问题