/**
* @author 拾光
* @version 1.0
*/
public class CAS实现test {
//用 volatile 修饰,线程可见性
static volatile int value = 0;
public static void main(String[] args) throws InterruptedException {
// test1();
test2();
}
//模仿cpu级别尝试修改值(无自旋,修改成功为true,否则为false)
public static void test1() throws InterruptedException {
new Thread(()->{
//模仿读取内存中的值,并将内存中的值拷贝一份到自己线程中的内存中
int current = value;
//sleep(100),模仿T1线程读取value内存信息之后,T2线程修改了内存中 value的值,来模仿T1线程内存的数据没有及时更新主内存中value的值
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean cas = CAS(current, current + 1);
System.out.println("T1 -->修改结果为:"+cas);
}).start();
//这里sleep的目的是:为了让线程Thread1先执行 int current = value这个程序
Thread.sleep(50);
new Thread(()->{
//模仿读取内存中的值,并将内存中的值拷贝一份到自己线程中的内存中
int current = value;
boolean cas = CAS(current, current + 1);
System.out.println("T2 -->修改结果为:"+cas);
}).start();
}
//模拟cpu级别:CAS自旋
public static void test2() throws InterruptedException {
Thread t1 = new Thread(() -> {
//模仿读取内存中的值,并将内存中的值拷贝一份到自己线程中的内存中
int current = value;
//sleep(100),模仿T1线程读取value内存信息之后,T2线程修改了内存中 value的值,来模仿T1线程内存的数据没有及时更新主内存中value的值
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//模拟线程不断读取内存中的信息,自旋操作
while(true){
//模仿重新读取
current = value;
boolean spinning = Spinning(current, current + 1);
//直到成功为止
if(spinning){
break;
}
}
});
t1.start();
//这里sleep的目的是:为了让线程Thread1先执行 int current = value这个程序
Thread.sleep(50);
Thread t2 = new Thread(() -> {
//模仿读取内存中的值,并将内存中的值拷贝一份到自己线程中的内存中
int current = value;
boolean cas = CAS(current, current + 1);
System.out.println("T2 -->修改结果为:" + cas);
});
t2.start();
t1.join();
t2.join();
System.out.println("最终:value结果为:"+value);
}
//核心:自旋函数,直到CAS函数返回true为止
public static boolean Spinning(int expected, int new_Value){
while(!cas(expected,new_Value)){}
return true;
}
public static boolean cas(int expected,int new_Value){
if(value==expected){
value = new_Value;
return true;
}
return false;
}
//CAS函数有两个参数:一个是期望值,一个是希望修改的值。所谓期望值就是线程中自己内存的那份从主存中拷贝的值,线程期望是自己内存的值和主存中的那份值是完全相等的,这样就不需要自旋的操作了
public static boolean CAS(int expected,int new_Value){
if(value==expected){
value = new_Value;
return true;
}
System.out.println("当前的值为:"+value+" 期望的值为:"+expected);
return false;
}
}
模拟CAS和CAS自旋
最新推荐文章于 2024-09-21 10:38:43 发布