import java.util.concurrent.atomic.AtomicInteger;
/**
 * @description: Atomic使用
 * @date: 2022/3/19 10:14
 * @version: 1.0
 */
public class AtomicDemo {
    public static void main(String[] args) {
        ////通过synchronized、volatile实现
//        demo demo = new demo();
//        for(int i=0;i<10;i++){
//            new Thread(demo).start();
//        }
        //使用AtomicInteger实现
        demo2 demo = new demo2();
        for(int i=0;i<10;i++){
            new Thread(demo).start();
        }
    }
    //通过synchronized、volatile实现
    public static class demo implements Runnable{
        private  volatile  int num=0;
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("num="+getNums());
        }
        public synchronized int getNums(){
            return  num ++;
        }
    }
    //使用AtomicInteger实现
    public static class demo2 implements Runnable{
        AtomicInteger num = new AtomicInteger();
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("num="+getNums());
        }
        public int getNums(){
            return  num.getAndIncrement();
        }
    }
}
                 
评论 (0)