Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement