// 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.ArrayList;
import java.util.List;

public class ThreadFun {
    public static class SharedState {
        public void doSomething() {
        }
    }
    public static class SomeWork {
        private SharedState ss;
        public SomeWork(SharedState ss) {
            this.ss = ss;
        }
        public void doSomethingHeavy() {
            try {
                synchronized(ss) { // synchronize access between threads
                    ss.doSomething();
                }
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        SharedState ss = new SharedState();
        List<SomeWork> work = new ArrayList<>();
        for(int i = 0; i < 1000; i++) {
            work.add(new SomeWork(ss));
        }
        // serial
        long t1 = System.currentTimeMillis();
        work.stream().forEach(w -> w.doSomethingHeavy());
        long t2 = System.currentTimeMillis();
        System.out.printf("Serial : %d\n", t2 - t1);
        // parallel
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "250"); // use 250 threads
        long t3 = System.currentTimeMillis();
        work.stream().parallel().forEach(w -> w.doSomethingHeavy()); // parallelize
        long t4 = System.currentTimeMillis();
        System.out.printf("Parallel : %d\n", t4 - t3);
    }
}
