// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
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;

public class ThreadFun implements Callable<String> {
    private static final String MSG = "It works!";
    private static final int N = 100;
    @Override
    public String call() throws InterruptedException {
        Thread.sleep(1000);
        return MSG;
    }
    private static void test(int poolsize) throws InterruptedException, ExecutionException {
        long t1 = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(poolsize);
        @SuppressWarnings("unchecked")
        Future<String>[] task = new Future[N];
        for(int i = 0; i < task.length; i++) {
            task[i] = es.submit(new ThreadFun());
        }
        for(int i = 0; i < task.length; i++) {
            String res = task[i].get();
            if(!res.equals(MSG)) throw new RuntimeException("Ooops");
        }
        es.shutdown();      
        long t2 = System.currentTimeMillis();
        System.out.printf("Executing %d tasks in %d threads took %.1f seconds\n", N, poolsize, (t2 - t1) / 1000.0);
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test(1);
        test(10);
        test(100);
    }
}
