// Java 乐观锁示例代码
import java.util.concurrent.atomic.AtomicInteger;
public class OptimisticLockExample {
// 使用 AtomicInteger 来模拟乐观锁
private AtomicInteger version = new AtomicInteger(0);
// 模拟数据更新操作
public boolean updateData(int expectedVersion, int newValue) {
// 获取当前版本号
int currentVersion = version.get();
// 检查预期版本号是否与当前版本号一致
if (expectedVersion == currentVersion) {
// 如果一致,则尝试更新版本号并返回成功
return version.compareAndSet(currentVersion, newValue);
} else {
// 如果不一致,说明数据已经被其他线程修改,返回失败
return false;
}
}
public static void main(String[] args) {
OptimisticLockExample example = new OptimisticLockExample();
// 线程1尝试更新数据
boolean result1 = example.updateData(0, 1);
System.out.println("Thread 1 update result: " + result1); // 应该输出 true
// 线程2尝试更新数据,但它的预期版本号是错误的
boolean result2 = example.updateData(0, 2);
System.out.println("Thread 2 update result: " + result2); // 应该输出 false
}
}
AtomicInteger:用于实现乐观锁的核心工具。AtomicInteger
提供了原子操作,确保在多线程环境下对整数的操作是线程安全的。
updateData 方法:这是模拟数据更新的方法。它接受两个参数:
expectedVersion
:调用方期望的数据版本号。newValue
:新的数据值。compareAndSet 方法:这是 AtomicInteger
的一个重要方法。它会比较当前的版本号是否与预期的版本号一致。如果一致,则更新为新的版本号,并返回 true
;如果不一致,则表示数据已经被其他线程修改过,返回 false
。
main 方法:演示了两个线程同时尝试更新数据的情况。线程1成功更新了数据,而线程2由于预期版本号不正确,更新失败。
这种机制被称为“乐观锁”,因为它假设冲突不会经常发生,只有在真正发生冲突时才会进行处理。
上一篇:java timestamp类型
下一篇:boolean在java中的用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站