Planforexams.com

Explain the Callable Interface with example in java

Callable Interface with example in java : Java offers two ways to create threads: one involves implementing the Runnable interface, and the other involves deriving from the Thread class. However, a crucial component of the Runnable interface implementation is missing because a thread cannot return something after its execution is complete, or when the run() method has finished. This capability is supported by the Java Callable interface.

Callable Interface in java : 

Callable Interface example in java

import java.util.concurrent.Callable;  
import java.util.Random;  
import java.util.concurrent.FutureTask;  
  
class PlanforexamsCallableInt implements Callable  
{  
	@Override  
	public Object call() throws Exception  
	{  
		/*
			The below code generates the Random Number.
			Random values generated till 20. 
			Random object is created and iterated to get 
			random values stored in randomNumValue
		*/
		Random randonNumObj = new Random();  
		Integer randomNumValue = randonNumObj.nextInt(20);  
		Thread.sleep(randomNumValue * 1000);  
 		return randomNumValue;  
	}  
}  
public class PlanforexamsCallableImpl  
{  
  public static void main(String argvs[]) throws Exception  
  {  
    FutureTask[] randomNumFutureTask = new FutureTask[10];  
    
    for (int itr = 0; itr < 10; itr++)  
    {  
      Callable callable = new JavaCallable();  
      randomNumFutureTask[itr] = new FutureTask(callable);  
      Thread threadObj = new Thread(randomNumFutureTask[itr]);  
      threadObj.start();  
    }  
    for (int itr = 0; itr < 10; itr++)  
    {  
      Object randomNumResult = randomNumFutureTask[itr].get();  
      System.out.println("Random Number printed form 0 to 19 is : " + randomNumResult);  
  
    }  
  }  
}  

The returned object, which is accessible to the main thread, must be stored after the call() method exits. It is crucial because the call() method’s result must be known by the main thread. The same goal is achieved by using a Future object. The result from a different thread is sent from the call() method and is stored in a Future object.
Future is an interface just like Callable. Therefore, it must be put into practice to be used with the callable interface in java for the object storage 

Exit mobile version