java AtomicInteger线程安全问题

查看:177
本文介绍了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 ########### 4
5 ########### 6
1 ########### 3
9 ########### 10
9 ########### 11
13 ########### 14
16 ########### 18
1 ########### 2
8 ########### 9
6 ########### 7
4 ########### 5
7 ########### 8
18 ########### 19
16 ########### 17
14 ########### 15
15 ########### 16
12 ########### 13
11 ########### 12
19 ########### 21
21 ########### 22
22 ########### 23
19 ########### 20
23 ########### 24
24 ########### 25

无法保证顺序,线程安全体现在哪里呢

解决方案

AtomicInteger 的incrementAndGet 保证对整数的递增和获取是原子的,

  1. 值+1

  2. 返回值

一个线程在这两个操作之间不会强行插入另外的线程

你要保证顺序,那么需要的是线程互斥

这篇关于java AtomicInteger线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆