码迷,mamicode.com
首页 > 编程语言 > 详细

并发编程(三)__模拟CAS算法

时间:2018-03-03 18:23:13      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:++   sys   this   expect   out   []   cas   zed   sync   

 1 /*
 2  * 模拟 CAS 算法
 3  */
 4 public class TestCompareAndSwap {
 5 
 6     public static void main(String[] args) {
 7         final CompareAndSwap cas = new CompareAndSwap();
 8         
 9         for (int i = 0; i < 10; i++) {
10             new Thread(new Runnable() {
11                 
12                 @Override
13                 public void run() {
14                     int expectedValue = cas.get();
15                     boolean b = cas.compareAndSet(expectedValue, (int)(Math.random() * 101));
16                     System.out.println(b);
17                 }
18             }).start();
19         }
20         
21     }
22     
23 }
24 
25 class CompareAndSwap{
26     private int value;
27     
28     //获取内存值
29     public synchronized int get(){
30         return value;
31     }
32     
33     //比较
34     public synchronized int compareAndSwap(int expectedValue, int newValue){
35         int oldValue = value;
36         
37         if(oldValue == expectedValue){
38             this.value = newValue;
39         }
40         
41         return oldValue;
42     }
43     
44     //设置
45     public synchronized boolean compareAndSet(int expectedValue, int newValue){
46         return expectedValue == compareAndSwap(expectedValue, newValue);
47     }
48 }

 

并发编程(三)__模拟CAS算法

标签:++   sys   this   expect   out   []   cas   zed   sync   

原文地址:https://www.cnblogs.com/dreamHighMjc/p/8497085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!