自旋锁
- A线程进来没问题,不解锁的情况下,B线程进来会空循环等待A解锁
package Lock.SpinlockDemo;
import java.util.concurrent.atomic.AtomicReference;
public class SpinlockA {
// int 0
//thread null
AtomicReference<Thread> atomicReference = new AtomicReference<>();
//加锁
public void lock() {
Thread thread = Thread.currentThread();
//自旋锁
// compareAndSet() 如果符合条件,就会set值。
// 返回true set成功
// 返回false 没set
boolean setSuccessful = atomicReference.compareAndSet(null, thread);
while (!setSuccessful) {
//第二个线程进来,setSuccessful为false,一直空循环
}
System.out.println(Thread.currentThread().getName() + "-->myLock");
}
//解锁
public void unlock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "-->myUnLock");
atomicReference.compareAndSet(thread, null);
}
}
package Lock.SpinlockDemo;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) throws InterruptedException {
SpinlockA spinlockA = new SpinlockA();
new Thread(() -> {
spinlockA.lock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (Exception e) {
e.printStackTrace();
} finally {
spinlockA.unlock();
}
}, "A").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
spinlockA.lock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
spinlockA.unlock();
}
}, "B").start();
}
}