Java自旋锁(Spin Lock)
是一种用于多线程同步的锁机制,通过反复检查某个条件(通常是一个共享变量的状态)而不是挂起线程来实现锁的获取。自旋锁的核心思想是让线程在尝试获取锁时保持活动状态,即进行“自旋”,以期望在短时间内锁能够被释放,从而避免线程上下文切换的开销。
import java.util.concurrent.atomic.AtomicBoolean;
public class SpinLock {
private final AtomicBoolean lock = new AtomicBoolean(false);
public void lock() {
// lock.compareAndSet(expectedValue, newValue)
// if expectedValue equals to initial value false will return true, else return false
while (!lock.compareAndSet(false, true)) {
// 自旋等待锁释放
}
}
public void unlock() {
lock.set(false);
}
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
Runnable task = () -> {
System.out.println(Thread.currentThread().getName() + " attempting to acquire lock");
spinLock.lock();
try {
System.out.println(Thread.currentThread().getName() + " acquired lock");
// 执行临界区代码
} finally {
spinLock.unlock();
System.out.println(Thread.currentThread().getName() + " released lock");
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
}
}