package com.yang;
public class TestVolatile {
public static void main(String[] args) {
final ThreadDemo td=new ThreadDemo();
for (int i = 0; i < 20; i++) {
new Thread(new Runnable() {
public void run() {
int excepted=td.getValue();
boolean b=td.comparedAndSet(excepted,(int)(Math.random()*101));
System.out.println(b);
}
}).start();
}
}
}
class ThreadDemo {
private int value;
public synchronized int getValue() {
return value;
}
//比较
public synchronized int compareAndSwap(int expected,int newValue) {
int oldValue = value;
if(oldValue==expected) {
this.value=newValue;
}
return oldValue;
}
public synchronized boolean comparedAndSet(int expected,int newValue) {
return expected==compareAndSwap(expected,newValue);
}
}
模拟CAS算法
最新推荐文章于 2024-06-10 10:59:38 发布