package jvm;

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

public class VolatileTest {

    public  static  volatile int race = 0;
    private static final Object lock = new Object();
    private static final ReentrantLock lock1 = new ReentrantLock();
    public static AtomicInteger race1 = new AtomicInteger(0);

    public static void increase() {
//       synchronized (lock) {
//           race++;
//       }
        race1.getAndAdd(1);
        lock1.lock();
        race++;
        lock1.unlock();
    }

    private static final int THREADS_COUNT = 20;

    static void main() {
        Thread[] threads = new Thread[THREADS_COUNT];
        for (int i = 0; i < THREADS_COUNT; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    increase();
                }
            });
            threads[i].start();
        }
        // for idea only. otherwise should be 1
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(race);
        System.out.println(race1.get());
    }
}
