首页 > 其他 > 详细

【转】AtomicReference与volatile的区别

时间:2019-04-16 18:12:24      阅读:108      评论:0      收藏:0      [点我收藏+]

来源:AtomicReference与volatile的区别

 

AtomicReference与volatile的在可见性上的意义是一致的。

volatile不能保证原子性,AutomicReference实现上则用了volatile和Unsafe.compareAndSwapObject()来分别保证可见性和原子性。

技术分享图片
 1 package org.liws;
 2 
 3 import java.util.concurrent.atomic.AtomicReference;
 4 import org.junit.Test;
 5 
 6 public class Snippet {
 7     
 8     private static volatile Integer volatileInt = 0;
 9     private static AtomicReference<Integer> atmicRef = new AtomicReference<Integer>(volatileInt);
10     
11     /** 验证volatile不能保证原子性 */
12     @Test public void test_volatile() throws InterruptedException {
13         for (int i = 0; i < 100; i++) {
14             new Thread(new Runnable() {
15                 @Override public void run() {
16                     for (int i = 0; i < 10000; i++) {
17                         volatileInt++;
18                     }
19                 }
20             }).start();
21         }
22         Thread.sleep(1000);
23         System.out.println(volatileInt); // something like 398793
24     }
25 
26     /** 验证test_AtomicReference能保证原子性 */
27     @Test public void test_AtomicReference() throws InterruptedException{
28         for (int i = 0; i < 100; i++) {
29             new Thread(new Runnable(){
30                 @Override public void run() {
31                     for (int i = 0; i < 10000; i++) {
32                         while (true) {
33                             Integer temp = atmicRef.get();
34                             if (atmicRef.compareAndSet(temp, temp + 1)) {
35                                 break;
36                             }
37                         }
38                     }
39                 }       
40             }).start();
41         }
42         Thread.sleep(1000);
43         System.out.println(atmicRef.get()); //1000000
44     }
45 }
View Code

 

 

 

【转】AtomicReference与volatile的区别

原文:https://www.cnblogs.com/apeway/p/10718473.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!