package com.example.demo.config;
import java.util.concurrent.locks.StampedLock;
//不能在一个线程中反复获取同一个锁
public class T {
private double x, y;
private final StampedLock sl = new StampedLock();
// an exclusively locked method 独占锁 写互斥
void move(double deltaX, double deltaY) {
long stamp = sl.writeLock();
try {
x += deltaX;
y += deltaY;
} finally {
sl.unlockWrite(stamp);
}
}
double distanceFromOrigin() { // A read-only method 只读锁
long stamp = sl.tryOptimisticRead();//返回验证的标记 是占有锁则返回0
double currentX = x, currentY = y;
// 是占有锁sl.validate(stamp) 返回false,说明发生锁的变化则需要重新获取 重新读取
if (!sl.validate(stamp)) {
stamp = sl.readLock();
try {
currentX = x;
currentY = y;
} finally {
sl.unlockRead(stamp);
}
}
return Math.sqrt(currentX * currentX + currentY * currentY);
}
//升级可以改为以乐观而非读取模式开始
/**
54 * 转换当前读戳为写戳,即上写锁
55 * 1.写锁戳,直接返回写锁戳
56 * 2.读锁戳且写锁可获得,则释放读锁,返回写锁戳
57 * 3.乐观读戳,当立即可用时返回写锁戳
58 * 4.其他情况返回0
59 */
//升级可以改为以乐观而非读取模式开始
void moveIfAtOrigin(double newX, double newY) { // upgrade Could instead start with optimistic, not read mode
long stamp = sl.readLock();
try {
while (x == 0.0 && y == 0.0) {
long ws = sl.tryConvertToWriteLock(stamp);
if (ws != 0L) {
stamp = ws;
x = newX;
y = newY;
break;
} else {
sl.unlockRead(stamp);
stamp = sl.writeLock();
}
}
} finally {
sl.unlock(stamp);
}
}