import java.util.concurrent.atomic.AtomicReference;
public class SpinLock {
private final AtomicReference<Thread> owner = new AtomicReference<>();
// 尝试获取锁
public void lock() {
Thread current = Thread.currentThread();
while (!owner.compareAndSet(null, current)) {
// 自旋等待,直到获取到锁
}
}
// 释放锁
public void unlock() {
Thread current = Thread.currentThread();
if (!owner.compareAndSet(current, null)) {
throw new IllegalStateException("Calling thread has not held the lock");
}
}
public static void main(String[] args) {
SpinLock spinLock = new SpinLock();
// 模拟两个线程竞争锁
Runnable task = () -> {
System.out.println(Thread.currentThread().getName() + " trying to acquire lock.");
spinLock.lock();
try {
System.out.println(Thread.currentThread().getName() + " acquired lock.");
// 执行临界区代码
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + " releasing lock.");
spinLock.unlock();
}
};
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
t1.start();
t2.start();
}
}
自旋锁的实现:
AtomicReference<Thread>
来存储当前持有锁的线程。lock()
方法中,使用 compareAndSet
方法尝试将 owner
设置为当前线程。如果设置成功,则表示获取到了锁;否则,线程会继续自旋(即循环)等待,直到获取到锁。解锁操作:
unlock()
方法中,确保只有当前持有锁的线程才能释放锁。如果当前线程不是持有锁的线程,则抛出异常。示例代码:
main
方法中,创建了两个线程 t1
和 t2
,它们都尝试获取同一个自旋锁。上一篇:java string 长度
下一篇:java重载和重写的区别
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站