public class MetodeSynchronized {
    private static class Counter {
        private long nilai = 0;
        private static long statis = 0;

        // Lock: objek instance Counter yang menjadi pemanggil method.
        synchronized void naik() {
            nilai++;
        }

        // Lock: objek Class<?> milik Counter (satu untuk seluruh instance).
        static synchronized void naikStatis() {
            statis++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Runnable tugasInstansi = () -> {
            for (int i = 0; i < 100_000; i++) {
                counter.naik();
            }
        };
        Runnable tugasStatis = () -> {
            for (int i = 0; i < 100_000; i++) {
                Counter.naikStatis();
            }
        };

        Thread a = new Thread(tugasInstansi, "teller-A");
        Thread b = new Thread(tugasInstansi, "teller-B");
        Thread c = new Thread(tugasStatis, "teller-C");
        Thread d = new Thread(tugasStatis, "teller-D");
        a.start();
        b.start();
        c.start();
        d.start();
        a.join();
        b.join();
        c.join();
        d.join();

        // Pembacaan setelah join() aman: join membangun happens-before.
        System.out.println("counter instance : " + counter.nilai);
        System.out.println("counter statis   : " + Counter.statis);
    }
}
