Examples AtomicInteger

AtomicInteger ensure atoms, visibility, orderly

public class AtomicIntegerTest {
    
    private static AtomicInteger  value =  new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new LoopVolatile());
        t1.start();

        Thread t2 = new Thread(new LoopVolatile2());
        t2.start();

        t1.join();
        t2.join();
        System.out.println("final val is: " + value); //20000
    }

    private static class LoopVolatile implements Runnable {
        public void run() {
            long val = 0;
            while (val < 10000L) {
                value.getAndIncrement();
                val++;
            }
        }
    }

    private static class LoopVolatile2 implements Runnable {
        public void run() {
            long val = 0;
            while (val < 10000L) {
                value.getAndIncrement();
                val++;
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/moris5013/p/11823442.html