Java: CAS ABA fixing
原创
©著作权归作者所有:来自51CTO博客作者wx62e0d796b5814的原创作品,请联系作者获取转载授权,否则将追究法律责任
package cas2;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
import sun.misc.Unsafe;
public class Person {
private static int i=0;
private static Person person=new Person();
private static AtomicStampedReference atomicStampedRef =
new AtomicStampedReference<>(i, 0);
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<1000;j++)
{
while(true)
{
int stamp = atomicStampedRef.getStamp(); //
Integer currentValue=atomicStampedRef.getReference();
boolean isCASSuccess = atomicStampedRef.compareAndSet(currentValue,currentValue+1,stamp,stamp +1);
if(isCASSuccess)
{
System.out.println(Thread.currentThread()+" " +atomicStampedRef.getReference());
break;
}
else
{
System.out.println(Thread.currentThread() +" CAS Failed.");
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<1000;j++)
{
while(true)
{
int stamp = atomicStampedRef.getStamp(); //
Integer currentValue=atomicStampedRef.getReference();
boolean isCASSuccess = atomicStampedRef.compareAndSet(currentValue,currentValue+1,stamp,stamp +1);
if(isCASSuccess)
{
System.out.println(Thread.currentThread()+" " +atomicStampedRef.getReference());
break;
}
else
{
System.out.println(Thread.currentThread() +" CAS Failed.");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
Thread t3=new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<1000;j++)
{
while(true)
{
int stamp = atomicStampedRef.getStamp(); //
Integer currentValue=atomicStampedRef.getReference();
boolean isCASSuccess = atomicStampedRef.compareAndSet(currentValue,currentValue+1,stamp,stamp +1);
if(isCASSuccess)
{
System.out.println(Thread.currentThread()+" " +atomicStampedRef.getReference());
break;
}
else
{
System.out.println(Thread.currentThread() +" CAS Failed.");
try {
Thread.sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
t.start();
t2.start();
t3.start();
t.join();
t2.join();
t3.join();
System.out.println(atomicStampedRef.getReference());
}
}