Thursday, April 18, 2024
HomeJavaDistinction between Callable and Runnable in Java? name() vs run() technique

Distinction between Callable and Runnable in Java? name() vs run() technique


For my part, the most important distinction between the Callable and Runnable interface is that Callable can return the end result of an operation carried out inside the decision() technique, which was one of many limitations of the Runnable interface. It has return kind as void()  which implies it can’t return any end result. 

 

One other vital distinction between the Runnable and Callable interfaces is the potential to throw checked exceptions. The Callable interface can throw checked exceptions as a result of its name technique throws Exceptions whereas run() technique would not throw any checked Exception. 
By the way in which, typically this query can be requested as a follow-up query of one other traditional distinction between Runnable and Thread in Java. Generally FutureTask is used together with Callable to get the results of asynchronous computation process carried out within the name() technique.

Callable vs Runnable interface in Java

As I defined the most important variations between a Callable and Runnable interface within the final part. Typically this query can be requested because the distinction between name() and run() technique in Java. All of the factors mentioned listed here are equally associated to that query as properly. Let’s examine them in level format for higher understanding :

1) The Runnable interface is older than Callable which is there from JDK 1.0, whereas Callable is added on Java 5.0.

2) Runnable interface has run() technique to outline process whereas Callable interface uses name() technique for process definition.

3) run() technique doesn’t return any worth, its return kind is void whereas the decision technique returns a price. The Callable interface is a generic parameterized interface and a Kind of worth is offered when an occasion of Callable implementation is created.

4) One other distinction within the run and name technique is that the run technique cannot throw checked exceptions whereas the decision technique can throw checked exceptions in Java.

Now that you’ve got seen the distinction between Runnable and Callable in Java, let’s have a look at one instance of each of them to really perceive how and when to make use of them:

Runnable vs Callable in Java

Callable Instance in Java

Right here is a straightforward instance of methods to use Callable in Java. On this instance, I’ve created a brand new ExecutorService with a set thread pool dimension of 1. We then create a new Callable that returns a string, and submit it to the ExecutorService utilizing the submit technique. 

This returns a Future object that we will use to get the results of the Callable as soon as it has accomplished. We block till the result’s out there by calling the get technique on the Future, after which print the end result. Lastly, it’s essential to shut down the ExecutorService.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableExample {

    public static void fundamental(String[] args) throws Exception {

        
        ExecutorService executor = Executors.newFixedThreadPool(1);

        
        Callable<String> process = () -> {
            System.out.println("Activity operating...");
            Thread.sleep(2000);
            return "Good day, World!";
        };

        
        Future<String> future = executor.submit(process);

        
        String end result = future.get();

        
        System.out.println("End result: " + end result);

        
        executor.shutdown();
    }
}

Once you run the code, it is going to print the next output:

Activity operating...
End result: Good day, World!

The Callable implementation merely prints “Activity operating…” to the console then sleeps for two seconds to simulate some work being achieved, after which returns the string “Good day, World!”

When the Future object is obtained and its get() technique known as, the thread will block till the result’s out there. On this case, the result’s the string “Good day, World!”, which is then printed to the console.

And, now let’s have a look at an instance of Runnable interface in Java:

Runnable Instance in Java

Right here is a straightforward instance of Runnable interface in Java. On this instance, I’ve create a brand new Runnable implementation referred to as MyRunnable which merely prints “Good day, World!” to the console. We then create a brand new Thread object and move within the MyRunnable occasion to its constructor. 

Lastly, we name the begin() technique on the Thread object to begin the thread and execute the run() technique of the MyRunnable occasion within the background. Once you run this code, it’s best to see “Good day, World!” printed to the console.

public class RunnableExample {

    public static void fundamental(String[] args) {
        
        MyRunnable myRunnable = new MyRunnable();

        
        Thread thread = new Thread(myRunnable);

        
        thread.begin();
    }

    personal static class MyRunnable implements Runnable {
        @Override
        public void run() {
            
            System.out.println("Good day, World!");
        }
    }
}

Once you run the above code , it is going to simply print “Good day World” as there’s nothing else contained in the run() technique. After this thread will come out of the run() technique and it is going to be completed. 

Additionally, Here’s a good abstract of all of the variations between Callable and Runnable in Java:

Runnable vs Callable in Java
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments