atomic保证内存变量的原子性

import java.util.concurrent.atomic.AtomicInteger;

/**
*
*atomic保证原子性的操作
*/
public class TestAtomic {

/**
 * 原子性
 *  AtomicInteger  可以保证原子操作的integer的类型
 *  synchronize    也可以保证原子性
 *  atomic要比synchronize性能要高
 */
public static AtomicInteger numb = new AtomicInteger(0);
//public static int numb = 0;

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

    for (int i = 0; i < 100; i++) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {

                    // incrementAndGet   numb++  每次只加一个
                    numb.incrementAndGet();//++每次只加一个
                }
            }
        }).start();

    }

    Thread.sleep(2000);
    System.out.println(numb);
}

}

“`

猜你喜欢

转载自blog.csdn.net/YZY_001/article/details/81843495