Java Executors ThreadPool example with Callable and Future.

package com.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Solution {

    public static void main(String[] args) throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(8);
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            futures.add(service.submit(new Task()));
        }
        for (Future<Integer> future: futures) {
            Integer result = future.get(); // blocking operation
            System.out.println(result);
        }
        service.shutdown();
    }

    static class Task implements Callable<Integer> {
        @Override
        public Integer call() {
            System.out.println("Thread " + Thread.currentThread().getId() + " is generating...");
            return new Random().nextInt();
        }
    }
}
TOPâ–˛
Post tagged with: java