package threaddemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class VolatileAtomicDemo {
    // will not guarantee added to 10000
    public static volatile int inc = 0;

    public static int inc2 = 0;

    public static AtomicInteger inc3 = new AtomicInteger(0);

    public static int inc4 = 0;
    public final ReentrantLock lock = new ReentrantLock();

    public void increase() {
        inc++;
        inc3.getAndAdd(1);
    }

    public synchronized void  safeIncrease() {
        inc2++;
    }

    public void safeIncrease2() {
        lock.lock();
        try {
            inc4++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        final VolatileAtomicDemo test = new VolatileAtomicDemo();
        for (int i = 0; i < 10; i++) {
            pool.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    test.increase();
                    test.safeIncrease();
                    test.safeIncrease2();
                }
            });
        }

        Thread.sleep(1000L);
        System.out.println(inc);
        System.out.println(inc2);
        System.out.println(inc3.get());
        System.out.println(inc4);
        pool.shutdown();
    }
}
