java乐观锁悲观锁demo
时间: 2023-12-07 13:39:08 浏览: 114
以下是Java中乐观锁和悲观锁的示例代码:
乐观锁示例代码:
```java
public class OptimisticLock {
private int count = 0;
public void increment() {
int oldValue = count;
while (!compareAndSet(oldValue, oldValue + 1)) {
oldValue = count;
}
}
public synchronized boolean compareAndSet(int oldValue, int newValue) {
if (count == oldValue) {
count = newValue;
return true;
}
return false;
}
}
```
悲锁示例代码:
```java
public class PessimisticLock {
//调用1
public synchronized void m1() {
//加锁后的业务逻辑...
}
//调用2
//保证多个线程使用的是同一个lock对象的前提下
ReentrantLock lock = new ReentrantLock();
public void m2() {
lock.lock();
try {
//操作同步资源
} finally {
lock.unlock();
}
}
}
```
阅读全文