Callable vs Runnable in java

This post describes the differences between callable and runnable

Code Schoool

4/27/20231 min read

Runnable and Callable

Runnable is used to create a thread in java ,in order to use runnable the class has to implement the runnable interface and provide an implementation for the run method, the disadvantage in using runnable is that the run method doesn't return any value. This disadvantage is removed by callable interface which has a call method which returns a value .

Difference between runnable and callable
  • Runnable can be used to create a thread but callable cannot be used for the same.

  • Runnable doesn't return any value while callable does.

  • Runnable has a run method which the implementing class has to implement while callable has a call method which the implementing class has to implement.

  • Call method of callable throws an exception but run method of runnable doesn't throw any exception.

Code showing callable functionality

import java.util.concurrent.Callable;

import java.util.concurrent.FutureTask;

class Demo implements Callable

{

public Object call() throws Exception

{

Integer value = 100;

Thread.sleep(5000);

value=value*10;

return value;

}

}

The above program simply multiplies an integer by 10 and returns the value which can be stored in another variable.

Code showing Runnable functionality

import java.util.Random;

import java.util.concurrent.Callable;

import java.util.concurrent.FutureTask;

class CallableExample implements Callable

{

public Object call() throws Exception

{

// Create random number generator

Random generator = new Random();

Integer randomNumber = generator.nextInt(5);

// To simulate a heavy computation,

// we delay the thread for some random time

Thread.sleep(randomNumber * 1000);

return randomNumber;

}

}