一.同步锁
我们还是用同步锁来实现存取款的例子:
package com.chanshuyi.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemo93 {
public static void main(String[] args) {
Account account = new Account(2300);
new DrawMoneyThread(account).start();
new DepositeThread(account).start();
}
}
class DepositeThread extends Thread{
private Account account;
public DepositeThread(Account account){
this.account = account;
}
@Override
public void run() {
//每次存200,10次共存2000
for(int i = 0; i < 10; i++){
account.deposit(200, i + 1);
//模拟存钱的时间间隔
try {
Thread.sleep((long)Math.random()*5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class DrawMoneyThread extends Thread{
private Account account;
public DrawMoneyThread(Account account){
this.account = account;
}
@Override
public void run() {
//每次取100,10次共取1000
for(int i = 0; i < 10; i++){
account.withdraw(100, i + 1);
//模拟取钱的时间间隔
try {
Thread.sleep((long)Math.random()*5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Account{
private Lock lock = new ReentrantLock();
//存钱
public void deposit(double amount, int i){
lock.lock();
try {
Thread.sleep((long)Math.random()*10000); //模拟存钱的延迟
this.balance = this.balance + amount;
System.out.println("***第" + i + "次,存入钱:" + amount);
System.out.println("***第" + i + "次,存钱后账户余额:" + this.balance);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
lock.unlock();
}
}
//取钱
public void withdraw(double amount, int i){
lock.lock();
try {
Thread.sleep((long)Math.random()*10000); //模拟取钱的延迟
if(this.balance >= amount){
this.balance = this.balance - amount;
System.out.println("第" + i + "次,取出钱:" + amount);
System.out.println("第" + i + "次,取钱后账户余额:" + this.balance);
}else{
System.out.println("第" + i + "次,余额不足");
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public Account(){
}
public Account(double balance){
this.balance = balance;
}
private double balance;
}
当我们进入需要同步的代码时,我们调用lock.lock()方法获取锁对象。当退出同步代码块时,使用lock.unlock()释放锁对象。下面是其中的一个输出:
第1次,取出钱:100.0
第1次,取钱后账户余额:2200.0
***第1次,存入钱:200.0
***第1次,存钱后账户余额:2400.0
第2次,取出钱:100.0
第2次,取钱后账户余额:2300.0
***第2