If a Thread require to return something after execution Callable interface. Callable interface contain only one method.
public Object call() throws Exception {
return null;
}
If a Callable object is submit to executor then after completing the job Thread returns and opbject of typr Future that is Future object can be used to retrive result from callable jobs.
import java.util.concurrent.*;
public class CallableExample implements Callable {
int number;
public CallableExample(int number) {
this.number = number;
}
@Override
public Object call() throws Exception {
System.out.println(Thread.currentThread().getName() + " Is responsible to calculate square of given number " + number );
return number* number;
}}
class CallableExampleRun{
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableExample [] tasks = {new CallableExample(3),new CallableExample(4),new CallableExample(5), new CallableExample(6),new CallableExample(7)};
ExecutorService service = Executors.newFixedThreadPool(3);
for(CallableExample task : tasks){
Future future = service.submit(task);
System.out.println(future.get());
}
service.shutdown();
}
}
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java
- Threads communication in Java
- Daemon Thread in Java
1 thought on “Callable and Future in Java”