代码demo
这是一把带超时时间的自旋锁,如果超时时间内依然无法获取锁,就直接返回false
package org.example.spinlock;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;/*** 自旋锁*/public class SpinLockTest {public static void main(String[] args) {SpinLock spinLock = SpinLock.get();for (int i = 0; i < 3; i++) {new Thread(()->{boolean success = spinLock.tryLock(2000);if (!success){System.out.println(Thread.currentThread().getName()+" get spin lock fail...");return;}System.out.println(Thread.currentThread().getName()+" get spin lock success...");try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+" TODO 业务逻辑...");spinLock.unLock();}).start();}}}class SpinLock{private SpinLock(){}private final static SpinLock spinLock = new SpinLock();public static SpinLock get(){return spinLock;}private final AtomicBoolean available = new AtomicBoolean(false);// 尝试获取锁,成功返回true,失败返回falsepublic boolean tryLock(long timeout){long deadline = System.currentTimeMillis()+timeout;while (System.currentTimeMillis()<deadline) {if (available.compareAndSet(false, true)){return true;}}return false;}public void unLock(){available.compareAndSet(true,false);}}
执行结果
Thread-0 get spin lock success...Thread-1 get spin lock fail...Thread-2 get spin lock fail...Thread-0 TODO 业务逻辑...
思考
自旋锁如何设计能够最大程度降低空转时间?
(后期有空去优化,可以参考JDK AQS底层的自旋机制)
