赞
踩
public class ReentrantLockUseAQS extends AbstractQueuedSynchronizer { @Override protected boolean tryAcquire(int arg) { if (compareAndSetState(0,1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } @Override protected boolean tryRelease(int arg) { if (compareAndSetState(1,0)) { setExclusiveOwnerThread(null); return true; } return false; } public static void main(String[] args) { final ReentrantLockUseAQS lock = new ReentrantLockUseAQS(); new Thread(() -> { // 获取锁 lock.acquire(1); System.out.println("T1成功获取锁," + LocalDateTime.now()); try { TimeUnit.SECONDS.sleep(3); System.out.println("T1执行完毕"); } catch (InterruptedException e) { e.printStackTrace(); }finally { // 释放锁 lock.release(1); System.out.println("T1释放了锁," + LocalDateTime.now()); } },"T1").start(); new Thread(() -> { try { // 让T1先获取锁 TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } lock.acquire(1); System.out.println("T2获取到锁," + LocalDateTime.now()); lock.release(1); },"T2").start(); } }
/**
* 模仿AQS写的锁
* 底层主要是LockSupport进行park跟unpark
* 使用Unsafe的CAS保证修改变量的原子性
*/
public
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。