java实现自旋锁(附完整源码)
时间: 2023-10-17 08:08:57 浏览: 96
以下是Java实现自旋锁的完整源码:
```java
import java.util.concurrent.atomic.AtomicReference;
public class SpinLock {
private AtomicReference<Thread> owner = new AtomicReference<>();
private int count = 0;
public void lock() {
Thread current = Thread.currentThread();
if (current == owner.get()) {
++count;
return;
}
while (!owner.compareAndSet(null, current)) {
}
}
public void unlock() {
Thread current = Thread.currentThread();
if (current == owner.get()) {
if (count > 0) {
--count;
} else {
owner.compareAndSet(current, null);
}
}
}
}
```
这个自旋锁使用AtomicReference来存储当前持有锁的线程,count变量用于记录当前线程重入的次数。当一个线程获得锁时,它会将owner设置为自己,当它释放锁时,它会将owner设置为null。如果一个线程已经持有锁,那么它可以重入锁,即多次调用lock()方法而不会阻塞。当一个线程释放锁时,如果它还重入了锁,则只需要将计数器减1,否则将owner设置为null以允许其他线程获得锁。
阅读全文