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

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


慕尼黑的夜晚无繁华
浏览 1461回答 2
2回答

慕村225694

AtomicInteger是一个原子类,顾名思义,它能保证一些操作是原子性的,比如说++、--等操作,这些操作在多线程的情况并不是线程安全的,但是使用原子类可以保证这些操作的原子性,从而来保证线程的安全性。
打开App,查看更多内容
随时随地看视频慕课网APP