手寫自旋鎖
public class SpinLockTest {
private volatile AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void spinLock(){
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null, thread)){}
System.out.println(thread.getName() + "已經獲取鎖");
}
public void unSpinLock(){
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(thread, null)){}
System.out.println(thread.getName() + "已經釋放鎖");
}
public static void main(String[] args) {
SpinLockTest spinLockTest = new SpinLockTest();
new Thread(new Runnable() {
@Override
public void run() {
spinLockTest.spinLock();
System.out.println("thread1 在執行");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
spinLockTest.unSpinLock();
}
}, "thread1").start();
new Thread(new Runnable() {
@Override
public void run() {
spinLockTest.spinLock();
System.out.println("thread2 在執行");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
spinLockTest.unSpinLock();
}
}, "thread2").start();
}
}