手写自旋锁
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
public class SpinLock {
AtomicReference<Thread> atomicReference = new AtomicReference<>();
public void lock() {
Thread thread = Thread.currentThread();
while (!atomicReference.compareAndSet(null, thread)) {}
}
public void unlock() {
Thread thread = Thread.currentThread();
atomicReference.compareAndSet(thread, null);
}
}
使用自旋锁
import java.util.concurrent.TimeUnit;
public class SpinLockTest {
public static void main(String[] args) {
SpinLock lock = new SpinLock();
new Thread(() -> {
lock.lock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}).start();
new Thread(() -> {
lock.lock();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}).start();
}
}
自旋锁的优缺点
- 自旋锁是反复检查锁变量是否可用,因此也是一个忙等待
- 自旋锁节省了线程上下文的切换
- 自旋锁会导致CPU增加负担
- 自旋锁一般用于会堵塞时间短的操作
此处锁的对象是当前线程,是为了方式其他线程解锁