Callable and Runnable Examples – ExecutorService

ExecutorService – Callable and Runnable Example
In this article let us see an example using Runnable and Callable tasks using ExecutorService.

Please refer here for Overview of ExecutorService

Runnable Example
Runnable does not return any value and cannot throw checked exceptions

Output:

NOTE:
From the output, we can notice how the executorservice works. We haven’t used Synchronized keyword in any of our methods, but ExecutorService makes sure one thread accesses the methods at a time.

Callable Example
Callable can return Future objects and can throw checked exceptions

Output:

We  have used future object to return string, Future object can return Integer, Boolean etc.
Sample example of using Boolean for the above code,

 

Leave a Reply

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