自旋锁
只要不找到期望值, 就会一直循环。
package JUC;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* 自旋锁
*/
public class Demo2 {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
// 加锁
public void myLock() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
// 自旋锁
while (atomicReference.compareAndSet(null, thread)) {
}
}
// 解锁
public void unmyLock() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
atomicReference.compareAndSet(thread, null);
}
public static void main(String[] args) throws Exception {
Demo2 lock = new Demo2();
new Thread(()->{
lock.myLock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (Exception e) {
e.getStackTrace();
} finally {
lock.unmyLock();
}
},"A").start();
TimeUnit.SECONDS.sleep(1);
new Thread(()->{
lock.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.getStackTrace();
} finally {
lock.unmyLock();
}
},"B").start();
}
}