Skip to content

Instantly share code, notes, and snippets.

@freeone3000
Created February 10, 2016 18:04
Show Gist options
  • Save freeone3000/483020dd106278227272 to your computer and use it in GitHub Desktop.
Save freeone3000/483020dd106278227272 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
public class CallableExample
{
public static void main(String[] args)
{
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
List<Future<Integer>> resultList = new ArrayList<>();
Random random = new Random();
for (int i=0; i<10; i++)
{
Integer number = random.nextInt(100);
FactorialCalculator calculator = new FactorialCalculator(number);
Future<Integer> result = executor.submit(calculator);
resultList.add(result);
}
for(Future<Integer> future : resultList)
{
try
{
System.out.println("Future result is - " + " - " + future.get() + "; And Task done is " + future.isDone());
}
catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
//shut down the executor service now
executor.shutdown();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
class FactorialCalculator implements Callable<Integer>
{
private Integer number;
public FactorialCalculator(Integer number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
int i = 0;
while(!Thread.terminated()) {
i++;
}
return i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment