此類屬於原子併發包,可以對引用類型進行原子無鎖操作
源碼分析
構造方法
//保證可見性和禁止指令重排序
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();
}
}