android 多线程访问整数问题,请使用AtomicInteger

AtomicInteger时随着jdk5.0出来的,它位于java.util.concurrent.atomic包下,AtomicInteger,一个提供原子操作的Integer的类。也就是说在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口,也就是说当有多个线程操作同一个变量时,使用AtomicInteger不会导致变量出现问题,而且比使用synchronized效率高,现在就看一个例子:

package cn.kge.com;import java.util.concurrent.atomic.AtomicInteger;public class AtomicDemo { public final static AtomicInteger atomicInteger = new AtomicInteger(1);public static void main(String[] args) throws InterruptedException {final Thread []threads = new Thread[10];for(int i = 0 ; i < 10 ; i++) {final int num = i;threads[i] = new Thread() {public void run() {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}int now = atomicInteger.incrementAndGet();System.out.println("我是线程:" + num + ",我得到值了,增加后的值为:" + now);}};threads[i].start();}for(Thread t : threads) {t.join();}System.out.println("最终运行结果:" + atomicInteger.get()); }}运行结果是:

我是线程:1,我得到值了,增加后的值为:2我是线程:2,,我得到值了,增加后的值为:3我是线程:0,我得到值了,增加后的值为:4我是线程:9,我得到值了,增加后的值为:5我是线程:5,我得到值了,增加后的值为:6我是线程:4,我得到值了,增加后的值为:7我是线程:8,我得到值了,增加后的值为:8我是线程:3,我得到值了,增加后的值为:9我是线程:7,我得到值了,增加后的值为:10我是线程:6,我得到值了,增加后的值为:11最终运行结果:11

为什么会是11呢?因为他构造函数中初始化就为1,然后有10个线程,每个线程都加1,就是11了,这就是单个线程执行时,atomicinteger加1不会出现问题,

AtomicInteger使用注意地方就是在你创建AtomicInteger对象时是作为成员变量使用的,不要再局部区域使用此对象!

尽量不要讲同事朋友的八卦。

android 多线程访问整数问题,请使用AtomicInteger

相关文章:

你感兴趣的文章:

标签云: