How to Convert a Runnable into a Callable in Java

In Java there are two ways to implement a class whose instances are to be executed by a thread.

  1. By implementing Runnable interface.
  2. By implementing Callable interface.

But what if you have a Runnable and you want to convert it into a Callable in Java at runtime. Executors class in Java provides utility methods to do that conversion.

  • callable(Runnable task)– Returns a Callable object that, when called, runs the given task and returns null.
  • callable(Runnable task, T result)– Returns a Callable object that, when called, runs the given task and returns the given result.

Converting Runnable to Callable in Java

1- Using the first method – callable(Runnable task)

Output

2- Using the second method- callable(Runnable task, T result)

Output

That’s all for the topic How to Convert a Runnable into a Callable in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.