Java多线程系列九——Atomic类

参考资料:https://fangjian0423.github.io/2016/03/16/java-AtomicInteger-analysis/
http://www.cnblogs.com/549294286/p/3766717.html

最近面试遇到一道编程题,要求两个线程交替打印[0,100]的数字,其中一个只打印奇数,另一个只打印偶数,并且给出特别明显的提示AtomicInteger,当时我在想简直是送分题啊,但事后回想由于手写又没有记得所有API,很多地方不完美,所以面试官最后让我解释一下,回来再用IDE写一遍就顺畅多了,解题思路:

  • 定义thread0输出奇数,thread1输出偶数
  • thread0执行时,若当前值为偶数则进入waiting状态并焕醒thread1
  • thread1执行时,若当前值为奇数则进入waiting状态并焕醒thread0
  • 循环执行上两步直到当前值达到100
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 测试AtomicInteger*/
public class AtomicIntegerTest {
    private static AtomicInteger num = new AtomicInteger(0);

    public static void main(String[] args) {
        MyThead thread0 = new MyThead(1);
        MyThead thread1 = new MyThead(0);
        thread0.start();
        thread1.start();
    }

    public static class MyThead extends Thread {

        private int v;

        public MyThead(int v) {
            this.v = v;
        }

        @Override
        public void run() {
            synchronized (num) {
                while (num.get() < 100) {
                    if (v == 1) {
                        if (num.get() % 2 == 0) {
                            try {
                                num.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.out.println(num.incrementAndGet());
                            num.notifyAll();
                        }
                    } else if (v == 0) {
                        if (num.get() % 2 == 1) {
                            try {
                                num.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.out.println(num.incrementAndGet());
                            num.notifyAll();
                        }
                    }
                }
            }
        }
    }
}

从AtomicInteger类源码可以看到,它定义了一个volatile的变量value用于存储值,而所有的操作都借助Unsafe类的操作来完成,Unsafe类的许多操作为CAS,可以理解为自带乐观锁,乐观锁就会存在ABA问题,但由于AtomicInteger保存的是int元素,在上题中背景下这个问题几乎可以忽略,故可认为它是线程安全的(若是用AtomicReference,ABA问题就可能带来致命问题,AtomicStampedReference类可用来解决这个问题)。

原文地址:https://www.cnblogs.com/hiver/p/7533629.html