0%

自旋锁-手动实现

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
* - AtomicReference原子性,底层实现CAS操作,可以对比普通对象的引用。
* - 使用unsafe.compareAndSwapObject来完成,支持普通对象的CAS操作。
*/
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
* - AtomicReference原子性,底层实现CAS操作,可以对比普通对象的引用。
* - 使用unsafe.compareAndSwapObject来完成,支持普通对象的CAS操作。
*/
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


----------- 本文结束啦感谢您阅读 -----------