为了账号安全,请及时绑定邮箱和手机立即绑定

java AtomicInteger线程安全问题

java AtomicInteger线程安全问题

public class TTTT implements Runnable{public static AtomicInteger ato = new AtomicInteger(1);int i = 1;public static void main(String[] args) {    TTTT t = new TTTT();    for (int i = 0;i<100; i++){        new Thread(t).start();    }}public void rrrr() throws Exception{    Thread.sleep(100);    int preVal = ato.get();    int val = ato.incrementAndGet();    System.out.println(preVal+" ########### "+val);}@Override public void run() {    try {        rrrr();    } catch (Exception e){    }}}AtomicInteger 的incrementAndGet是线程安全的计数方法上面代码执行结果是:1 ########### 45 ########### 61 ########### 39 ########### 109 ########### 1113 ########### 1416 ########### 181 ########### 28 ########### 96 ########### 74 ########### 57 ########### 818 ########### 1916 ########### 1714 ########### 1515 ########### 1612 ########### 1311 ########### 1219 ########### 2121 ########### 2222 ########### 2319 ########### 2023 ########### 2424 ########### 25无法保证顺序,线程安全体现在哪里呢
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

AtomicInteger是一个原子类,顾名思义,它能保证一些操作是原子性的,比如说++、--等操作,这些操作在多线程的情况并不是线程安全的,但是使用原子类可以保证这些操作的原子性,从而来保证线程的安全性。

查看完整回答
反对 回复 2018-10-14
  • 2 回答
  • 0 关注
  • 1454 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信