AtomicInteger的使用

AtomicInteger是线程安全的,那么我们就把它和Integer对比一下。思路如下:

创建两个线程,每个线程中对同一个对象执行10000次加法,打印最后的输出结果,代码如下。

package thread.learn;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by liujinhong on 2017/3/5.
 */
public class AtomicIntegerTest {
    public static void main(String[] args) {
//        myThread2 my2 = new myThread2();
//        Thread thread1 = new Thread(my2);
//        Thread thread2 = new Thread(my2);
//
//        thread1.start();
//        thread2.start();
//
//        while (thread1.isAlive() || thread2.isAlive()) {
//
//        }

//        System.out.println(my2.atomicInteger);
        myThread3 my3 = new myThread3();
        Thread thread3 = new Thread(my3);
        Thread thread4 = new Thread(my3);

        thread3.start();
        thread4.start();

        while (thread3.isAlive() || thread4.isAlive()) {

        }

        System.out.println(my3.integer);
    }
}
//对AtomicInteger进行操作
class myThread2 implements Runnable {
    public AtomicInteger atomicInteger = new AtomicInteger(0);
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            atomicInteger.addAndGet(1);
        }
    }
}
//对Integer进行操作
class myThread3 implements Runnable {
    public Integer integer = new Integer(0);
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            integer++;
        }
    }
}

我们创建了两个实现了Runnable接口的对象,其中一个定义了一个AtomicInteger对象,另一个使用普通的包装类。

output:

my3.integer的结果是不确定的,每次的运行结果都小于20000.

my2.atomicInteger是线程安全的,每次的运行结果都是正好等于20000,不会出错。

转载于:https://www.cnblogs.com/liujinhong/p/6506968.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值