1. Runnable interface
1.1 Definition of Runnable
Runnable
is a functional interface in Java that defines arun()
Method, used to encapsulate thread's task logic.Runnable
The 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 value:
Runnable
ofrun()
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 throwing:
run()
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 tasks:
Runnable
It 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 simpleRunnable
task and pass it toThread
Object to execute.run()
The code inside the method will be executed in a new thread.
2. Callable interface
2.1 Definition of Callable
Callable
is another functional interface in Java, which is located inIn the package. and
Runnable
different,Callable
ofcall()
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:
Callable
ofcall()
The method returns a result. The type of return value is from the generic parameterV
Specified. - Can throw check exceptions:
call()
Method allows the check exception to be thrown, which makesCallable
Suitable for handling complex tasks that require throwing exceptions. - Usually with
Future
Use with:Callable
The interface is usually withFuture
Use the interface together, throughFuture
The 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,Callable
Task returns aInteger
result. We passedExecutorService
Submit the task and useFuture
Object 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
-
Runnable
:Runnable
Interfacerun()
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. -
Callable
:Callable
Interfacecall()
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
Runnable
:Runnable
Interfacerun()
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.Callable
:Callable
Interfacecall()
Methods allow check exceptions to be thrown, so exceptions can be declared directly in the method signature and handled outside the method. This makesCallable
More suitable for handling tasks that may throw exceptions.
3.3 Framework for use
-
Runnable
:Runnable
Usually withThread
orExecutorService
Use together. It can be passed directly toThread
Object or throughExecutorService
implement. -
Callable
:Callable
Usually withExecutorService
andFuture
Use together. pass()
Method SubmitCallable
task and return aFuture
Object, 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, use
Runnable
Execute 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 used
Runnable
To 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, use
Callable
Defines 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 operation:
Callable
It can be used to perform asynchronous operations such as asynchronous network requests, asynchronous database queries, etc. After the task is completed, you can passFuture
Get the results. -
Complex tasks: When a task may throw a check exception, or needs to deal with complex business logic,
Callable
CompareRunnable
More 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 lightweight:
Runnable
The interface is simple to design and easy to use, and is suitable for tasks that do not require return results. -
Widely used:
Runnable
It is an interface introduced by Java in the early days, and almost all Java multithreaded frameworks support it.Runnable
。
shortcoming:
-
No return value:
Runnable
The execution result of the task cannot be returned, and the scope of application is limited. -
Inconvenient exception handling:
Runnable
Exception 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 value:
Callable
Supports return results, suitable for tasks that need to obtain execution results. -
Easy to handle exceptions:
Callable
Allows to throw check exceptions, which facilitates handling of complex business logic and exception situations.
shortcoming:
-
Relatively complex:and
Runnable
compared to,Callable
The use is slightly more complicated and requiresExecutorService
andFuture
Use together.
6. Conclusion
Runnable
andCallable
They are two commonly used interfaces in Java multithreaded programming, which are used to define tasks that can be executed concurrently.Runnable
Suitable for performing simple tasks that do not require return results, andCallable
Suitable for complex tasks that require a result to be returned.
In actual development, choose to useRunnable
stillCallable
Depend on the specific application scenario. If your task does not need to return results, and does not need to handle checking exceptions,Runnable
It is a simple and effective choice. If your task needs to return results and may throw exceptions,Callable
It 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!