SoFunction
Updated on 2025-04-13

Analysis of the difference between runnable and callable in Java

1. Runnable interface

1.1 Definition of Runnable

Runnableis a functional interface in Java that defines arun()Method, used to encapsulate thread's task logic.RunnableThe interface is very simple, it does not return results and does not throw check exceptions.

@FunctionalInterface
public interface Runnable {
    void run();
}

1.2 Features of Runnable

  • No return valueRunnableofrun()The method has no return value. If you need to get the results of task execution, you usually need to use other mechanisms, such as using shared variables or through callback mechanisms.
  • Check for exceptions without throwingrun()Methods do not allow checked exceptions to be thrown, which means you need torun()The method internally captures and handles all checked exceptions.
  • Suitable for simple tasksRunnableIt is often used to define simple tasks, especially those that do not need to return results or handle exceptions.

1.3 Example of using Runnable

public class RunnableExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            ("Executing task in Runnable");
        };
        Thread thread = new Thread(task);
        ();
    }
}

In this example, we create a simpleRunnabletask and pass it toThreadObject to execute.run()The code inside the method will be executed in a new thread.

2. Callable interface

2.1 Definition of Callable

Callableis another functional interface in Java, which is located inIn the package. andRunnabledifferent,Callableofcall()The method can return a result and can throw a check exception.

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

2.2 Features of Callable

  • There is a return value:Callableofcall()The method returns a result. The type of return value is from the generic parameterVSpecified.
  • Can throw check exceptions:call()Method allows the check exception to be thrown, which makesCallableSuitable for handling complex tasks that require throwing exceptions.
  • Usually withFutureUse with:CallableThe interface is usually withFutureUse the interface together, throughFutureThe object obtains the execution result of the task or the completion status of the processing task.

2.3 Example of using Callable

import ;
import ;
import ;
import ;
import ;
public class CallableExample {
    public static void main(String[] args) {
        Callable<Integer> task = () -> {
            ("Executing task in Callable");
            return 123;
        };
        ExecutorService executor = ();
        Future<Integer> future = (task);
        try {
            Integer result = ();
            ("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            ();
        } finally {
            ();
        }
    }
}

In this example,CallableTask returns aIntegerresult. We passedExecutorServiceSubmit the task and useFutureObject gets the execution result of the task.()The method blocks the current thread until the task completes and returns the result.

3. The difference between Runnable and Callable

3.1 Return value

  • RunnableRunnableInterfacerun()The method has no return value. It is usually used to perform tasks that do not need to return results, such as updating shared variables, writing to logs, etc.
  • CallableCallableInterfacecall()The method has a return value. It is suitable for scenarios where you need to return the calculation result or need to get the result after performing certain tasks.

3.2 Exception handling

RunnableRunnableInterfacerun()Methods do not allow check exceptions to be thrown. Ifrun()The method needs to handle checking exceptions, and must be captured and processed within the method.CallableCallableInterfacecall()Methods allow check exceptions to be thrown, so exceptions can be declared directly in the method signature and handled outside the method. This makesCallableMore suitable for handling tasks that may throw exceptions.

3.3 Framework for use

  • RunnableRunnableUsually withThreadorExecutorServiceUse together. It can be passed directly toThreadObject or throughExecutorServiceimplement.
  • CallableCallableUsually withExecutorServiceandFutureUse together. pass()Method SubmitCallabletask and return aFutureObject, used to obtain the results of a task or check the status of a task.

3.4 Application scenarios

  • Runnable: Suitable for simple tasks that do not need to return results, such as timing tasks, background logging tasks, UI update tasks, etc.
  • Callable: Suitable for complex tasks that need to return results, such as data processing, computing tasks, network requests, etc.

4. Application scenarios of Runnable and Callable

4.1 Runnable application scenarios

  • Backstage tasks: In UI applications, useRunnableExecute some background tasks, such as loading data, performing time-consuming operations, etc. These tasks do not need to return results, they just need to be completed in the background.
  • Timing tasks: In the timing task scheduler, it can be usedRunnableTo define tasks that are executed periodically, such as timed update caches, timed cleaning of log files, etc.
  • Simple parallel tasks: You can use it when multiple tasks need to be executed in parallel but don't care about their return results.Runnable. For example, starting multiple threads to process different log files simultaneously.

4.2 Application scenarios of Callable

  • parallel computing: In parallel computing, useCallableDefines the task that needs to return the result. For example, when processing data in parallel, each task can return the processed results and then merge these results to obtain the final result.
  • Asynchronous operationCallableIt can be used to perform asynchronous operations such as asynchronous network requests, asynchronous database queries, etc. After the task is completed, you can passFutureGet the results.
  • Complex tasks: When a task may throw a check exception, or needs to deal with complex business logic,CallableCompareRunnableMore suitable because it can return the result and throw an exception.

5. Pros and cons of Runnable and Callable

5.1 Pros and cons of Runnable

advantage

  • Simple and lightweightRunnableThe interface is simple to design and easy to use, and is suitable for tasks that do not require return results.
  • Widely usedRunnableIt is an interface introduced by Java in the early days, and almost all Java multithreaded frameworks support it.Runnable

shortcoming

  • No return valueRunnableThe execution result of the task cannot be returned, and the scope of application is limited.
  • Inconvenient exception handlingRunnableException checking is not allowed, so additional code may be required when handling exceptions.

5.2 Pros and cons of Callable

advantage

  • There is a return valueCallableSupports return results, suitable for tasks that need to obtain execution results.
  • Easy to handle exceptionsCallableAllows to throw check exceptions, which facilitates handling of complex business logic and exception situations.

shortcoming

  • Relatively complex:andRunnablecompared to,CallableThe use is slightly more complicated and requiresExecutorServiceandFutureUse together.

6. Conclusion

RunnableandCallableThey are two commonly used interfaces in Java multithreaded programming, which are used to define tasks that can be executed concurrently.RunnableSuitable for performing simple tasks that do not require return results, andCallableSuitable for complex tasks that require a result to be returned.

In actual development, choose to useRunnablestillCallableDepend on the specific application scenario. If your task does not need to return results, and does not need to handle checking exceptions,RunnableIt is a simple and effective choice. If your task needs to return results and may throw exceptions,CallableIt will be more suitable.

This is the end of this article about the difference between runnable and callable in Java. For more information about the differences between runnable and callable in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!