Java — Callable and Future | Code Factory

Object call() throws Exception
package com.example.thread;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author code.factory
*
*/
public class CallableTest {
public static void main(String... args) throws InterruptedException, ExecutionException {
MyCallable jobs[] = {
new MyCallable(10),
new MyCallable(20),
new MyCallable(30),
new MyCallable(40),
new MyCallable(50),
new MyCallable(60),
};
ExecutorService service = Executors.newFixedThreadPool(3);
for(MyCallable job : jobs) {
Future f = service.submit(job);
System.out.println(f.get());
}
service.shutdown();
}
}
class MyCallable implements Callable {
int no;
public MyCallable(int no) {
this.no = no;
}

public Object call() throws Exception {
System.out.print(Thread.currentThread().getName() + " sum of first " + no + " numbers : ");
int sum = 0;
for(int i=0; i<no; i++) {
sum = sum + i;
}
return sum;
}
}
pool-1-thread-1 sum of first 10 numbers : 45
pool-1-thread-2 sum of first 20 numbers : 190
pool-1-thread-3 sum of first 30 numbers : 435
pool-1-thread-1 sum of first 40 numbers : 780
pool-1-thread-2 sum of first 50 numbers : 1225
pool-1-thread-3 sum of first 60 numbers : 1770

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store