1 银行类代码
class Bank {
private volatile int count = 100; // 账户余额
// 存钱
public void setCount(int count) {
this.count = count;
}
// 取钱
public int getCount(){
return this.count;
}
}
2 存取50块钱各一次
1乐观锁代码
使用CAS想法实现乐观锁:
- 使用whil循环实现自旋转检查;
- compareAndSwap方法实现旧值对比和设置更新后的数值;
public class optimiclock {
public static void main(String[] args) throws InterruptedException {
Bank bank = new Bank();
// 存50块钱
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
int oldValue = bank.getCount();
int newValue = oldValue + 50;
if (compareAndSwap(bank, oldValue, newValue)) {
break;
}
}
}
}).start();
// 取出50
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
int oldValue = bank.getCount();
int newValue = oldValue - 50;
if (compareAndSwap(bank, oldValue, newValue)) {
break;
}
}
}
}).start();
Thread.sleep(1000);
System.out.println(bank.getCount());
}
public static boolean compareAndSwap(Bank bank, int oldValue, int newValue) {
if (bank.getCount() != oldValue) {
return false;
}
bank.setCount(newValue);
return true;
}
}
2 悲观锁实现
- 使用synchronized实现
- 关键在于使用
Object lock = new Object();
,令存取两个线程使用同一把锁
public class pessimisticLock {
public static void main(String[] args) throws InterruptedException {
Bank bank = new Bank();
Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
bank.setCount(bank.getCount() + 50);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
bank.setCount(bank.getCount() - 50);
}
}
}).start();
Thread.sleep(1000);
System.out.println(bank.getCount());
}
}