java中volatile不能保证线程安全(实例讲解)

2025-05-29 0 89

今天打了打代码研究了一下java的volatile关键字到底能不能保证线程安全,经过实践,volatile是不能保证线程安全的,它只是保证了数据的可见性,不会再缓存,每个线程都是从主存中读到的数据,而不是从缓存中读取的数据,附上代码如下,当synchronized去掉的时候,每个线程的结果是乱的,加上的时候结果才是正确的。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35
/**

*

* 类简要描述

*

* <p>

* 类详细描述

* </p>

*

* @author think

*

*/

public class VolatileThread implements Runnable {

private volatile int a = 0;

@Override

public void run() {

// TODO Auto-generated method stub

// synchronized (this) {

a = a + 1;

System.out.println(Thread.currentThread().getName() + ":----" + a);

try {

Thread.sleep(100);

a = a + 2;

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + ":----" + a);

// }

}

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54
/**

*

* 类简要描述

*

* <p>

* 类详细描述

* </p>

*

* @author think

*

*/

public class VolatileMain {

public static void main(String[] args) {

VolatileThread s = new VolatileThread();

Thread t1 = new Thread(s);

Thread t2 = new Thread(s);

Thread t3 = new Thread(s);

Thread t4 = new Thread(s);

t1.start();

t2.start();

t3.start();

t4.start();

/* 同步的结果

Thread-2:----1

Thread-2:----3

Thread-0:----4

Thread-0:----6

Thread-3:----7

Thread-3:----9

Thread-1:----10

Thread-1:----12*/

/*

去掉同步的结果

Thread-0:----1

Thread-1:----2

Thread-2:----3

Thread-3:----4

Thread-0:----8

Thread-3:----10

Thread-1:----10

Thread-2:----12*/

}

}

以上这篇java中volatile不能保证线程安全(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/Think-007/p/7084375.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java中volatile不能保证线程安全(实例讲解) https://www.kuaiidc.com/115104.html

相关文章

发表评论
暂无评论