Create thread using java.util.concurrent.Callable
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; class MyCallable implements Callable { @Override public String call() throws Exception{ System.out.println("\nBegin Work"); try { System.out.println("Thread is working..."); } catch (Exception e) { System.out.println("Error while running thread. Reason: " + e.getMessage()); } System.out.println("Work Finished"); return "SUCCESS"; } } public class CallableFlight { public static void main(String[] array) { MyCallable myCallable = new MyCallable(); FutureTask futureTask = new FutureTask(myCallable); futureTask.run(); try { System.out.println("Thread response: "+futureTask.get()); } catch (Exception e) { System.out.println("Error while taking response.
Reason: "+ e.getMessage()); } } }
Output
Begin Work Thread is working... Work Finished Thread response: SUCCESS
Callable interface is introduced in JDK 1.5.
It is available in java.util.concurrent package.
The call() method provided by callable interface has return type and also it throws Exception.
You can execute a callable thread using FutureTask object.
It required to pass the callable implementer class object into FutureTask constructor.
Then call the run() method on the FutureTastk, It will make the thread running.
To get the value returned by callable thread, call the get() method on FutureTask object.