// 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) 
public class ToSyncOrNotToSync {
    private static final int NTHREAD = 100;
    private static final int NREP = 1000000;
    private int n;
    public void incrN() {
        n++;
    }
    public void testNonSynch() throws InterruptedException {
        n = 0;
        Thread[] t = new Thread[NTHREAD];
        for(int i = 0; i < t.length; i++) {
            t[i] = new NonSyncThread(this, NREP);
        }
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < t.length; i++) {
            t[i].start();
        }
        for(int i = 0; i < t.length; i++) {
            t[i].join();
        }
        long t2 = System.currentTimeMillis();
        System.out.println((NTHREAD*NREP) + "=" + n + " in " + (t2-t1) + " ms");
    }
    public void testSynch() throws InterruptedException {
        n = 0;
        Thread[] t = new Thread[NTHREAD];
        for(int i = 0; i < t.length; i++) {
            t[i] = new SyncThread(this, NREP);
        }
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < t.length; i++) {
            t[i].start();
        }
        for(int i = 0; i < t.length; i++) {
            t[i].join();
        }
        long t2 = System.currentTimeMillis();
        System.out.println((NTHREAD*NREP) + "=" + n + " in " + (t2-t1) + " ms");
    }
    public static void main(String[] args) throws InterruptedException {
        ToSyncOrNotToSync o = new ToSyncOrNotToSync();
        o.testNonSynch();
        o.testSynch();
    }
}

class NonSyncThread extends Thread {
    private ToSyncOrNotToSync parent;
    private int nrep;
    public NonSyncThread(ToSyncOrNotToSync parent, int nrep) {
        this.parent = parent;
        this.nrep = nrep;
    }
    public void run() {
        for(int i = 0; i < nrep; i++) {
            parent.incrN();
        }
    }
}

class SyncThread extends Thread {
    private ToSyncOrNotToSync parent;
    private int nrep;
    public SyncThread(ToSyncOrNotToSync parent, int nrep) {
        this.parent = parent;
        this.nrep = nrep;
    }
    public void run() {
        for(int i = 0; i < nrep; i++) {
            synchronized(parent) {
                parent.incrN();
            }
        }
    }
}
