// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TP18 {
    public static void something() {
        try {
            Thread.sleep(1); // simulate work taking time
        } catch(InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    private static final int NTASK = 1 << 16;
    public static void testR(int nthreads) throws InterruptedException, ExecutionException {
        long t1 = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(nthreads);
        List<Future<Void>> flst = new ArrayList<Future<Void>>();
        for(int i = 0; i < NTASK; i++) {
            flst.add(es.submit(() -> { something(); return null; }));
        }
        for(Future<Void> f : flst) {
            f.get();
        }
        es.shutdown();
        long t2 = System.currentTimeMillis();
        System.out.printf("Real threads (%d) : %d\n", nthreads, t2 - t1);
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        for(int i = 2; i < 16; i++) {
            testR(1 << i);
        }
    }
}
