/** * park+自旋 */ public class ParkLock implements ILock { private volatile int status = 0; private Queue<Thread> queue = new ConcurrentLinkedQueue<>();
public void lock() { while (!compareAndSwap(1)) { System.out.println(Thread.currentThread().getName() + "waiting"); threadPark(); } System.out.println(Thread.currentThread().getName() + "lock,"); }
private void threadPark() { queue.add(Thread.currentThread()); status = 1; LockSupport.park(); }
private boolean compareAndSwap(int newValue) { if (0 == status) { status = newValue; return true; } return false; }
public void unlock() { status = 0; Thread poll = queue.poll(); LockSupport.unpark(poll); System.out.println(Thread.currentThread().getName() + "unlock"); } }