// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package threads;

public class Basic2 {
    public static class Data {
        private String s;
        public Data(String s) {
            this.s = s;
        }
        public String getS() {
            return s;
        }
        public void setS(String s) {
            this.s = s;
        }
    }
    public static class Processor implements Runnable {
        private Data d;
        public Processor(Data d) {
            this.d = d;
        }
        @Override
        public void run() {
            try {
                // simulate a lot of work that takes 0.1 second
                String s = d.getS();
                Thread.sleep(100);
                d.setS(s + 'X');
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void test(int njobs, int nthreads) {
        // setup data
        Data[] d = new Data[njobs];
        for(int i = 0; i < njobs; i++) {
            d[i] = new Data("X");
        }
        // process
        long t1 = System.currentTimeMillis();
        int k = 0;
        for(int i = 0; i < njobs / nthreads; i++) {
            // create threads
            Thread[] t = new Thread[nthreads];
            for(int j = 0; j < nthreads; j++) {
                t[j] = new Thread(new Processor(d[k]));
                k++;
            }
            // start threads
            for(int j = 0; j < nthreads; j++) {
                t[j].start();
            }
            // wait for threads to complete
            for(int j = 0; j < nthreads; j++) {
                try {
                    t[j].join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("%d jobs executing in %d threads : %.1f seconds\n", njobs, nthreads, (t2 - t1) / 1000.0);
        // check data
        for(int i = 0; i < njobs; i++) {
            if(!d[i].getS().equals("XX")) System.out.println("Ooops");
        }
    }
    public static void main(String[] args) {
        test(256, 1);
        test(256, 2);
        test(256, 4);
        test(256, 8);
        test(256, 16);
        test(256, 32);
        test(256, 64);
    }
}
