此类属于原子并发包,可以对引用类型进行原子无锁操作
源码分析
构造方法
//保证可见性和禁止指令重排序
private volatile V value;
/**
* 用给定的对象创造一个引用原子类型
*
* @param initialValue the initial value
*/
public AtomicReference(V initialValue) {
value = initialValue;
}
/**
* 创造一个给定值为null的引用原子
*/
public AtomicReference() {
}
重要方法
/**
* 得到当前操作的对象
*
* @return the current value
*/
public final V get() {
return value;
}
/**
* 设置1当前操作对象
*
* @param newValue the new value
*/
public final void set(V newValue) {
value = newValue;
}
/**
*
* 如果当前值和预期值相等,就更新新值
* @param 预期值
* @param 更新值
* @return 当前值和预期值相等就返回true,否则返回fasle
*/
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
/**
*
* 原子设置更新
* @param newValue the new value
* @return 先前值
*/
@SuppressWarnings("unchecked")
public final V getAndSet(V newValue) {
return (V)unsafe.getAndSetObject(this, valueOffset, newValue);
}
案例分析
用AtomicReference实现自旋操作
/**
* 描述: 自旋锁
*/
public class SpinLock {
private AtomicReference<Thread> sign = new AtomicReference<>();
public void lock() {
Thread current = Thread.currentThread();
while (!sign.compareAndSet(null, current)) {
System.out.println("自旋获取失败,再次尝试");
}
}
public void unlock() {
Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁");
spinLock.lock();
System.out.println(Thread.currentThread().getName() + "获取到了自旋锁");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
spinLock.unlock();
System.out.println(Thread.currentThread().getName() + "释放了自旋锁");
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}