yield + 自旋实现同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class YieldLock {
AtomicReference<Thread> lock = new AtomicReference<>();
public void lock1() { Thread t = Thread.currentThread(); while (!lock.compareAndSet(null, t)) { t.yield(); System.out.println(t.getName() + "***************** 尝试获取锁失败"); } System.out.println(t.getName() + "***************** 获取锁"); }
public void unLock() { Thread t = Thread.currentThread(); System.out.println(t.getName() + "***************** 释放锁"); lock.compareAndSet(t, null); } }
|
sleep + 自旋方式实现同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class SleepLock {
AtomicReference<Thread> lock = new AtomicReference<>();
public void lock1() { Thread t = Thread.currentThread(); while (!lock.compareAndSet(null, t)) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(t.getName() + "***************** 空转"); } System.out.println(t.getName() + "***************** 获取锁"); }
public void unLock() { Thread t = Thread.currentThread(); System.out.println(t.getName() + "***************** 释放锁"); lock.compareAndSet(t, null); } }
|
参考:
https://blog.csdn.net/java_lyvee/article/details/98966684