Atomic原子类的使用

admin
2022-03-19 / 0 评论 / 109 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月19日,已超过774天没有更新,若内容或图片失效,请留言反馈。
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();
        }
    }

}
6

评论 (0)

取消