spinlock
自定义一个锁测试
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference();
//加锁
public void myLock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "MyLock");
//自旋锁
while (!atomicReference.compareAndSet(null, thread)) {
}
}
// 解锁
public void myUnLock() {
Thread thread = Thread.currentThread();
System.out.println(Thread.currentThread().getName() + "myUnLock");
atomicReference.compareAndSet(thread, null);
}
}
public class Test01 {
public static void main(String[] args) throws InterruptedException {
/*ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.lock();
reentrantLock.unlock();*/
// 底层使用的自旋锁CAS
SpinLockDemo lock = new SpinLockDemo();
new Thread(() -> {
lock.myLock();
try {
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "T1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
lock.myLock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.myUnLock();
}
}, "T2").start();
}
}
原文:https://www.cnblogs.com/saxonsong/p/14731640.html