Original : North American block king

public class Bank{   //银行余额   private int balance;
public Bank(int balance){ this.balance = balance; }
//用户提款 public void withdraw (int value) { try { Thread.sleep(300); //0.3秒的模拟时延 } catch (InterruptedException e) { e.printStackTrace(); } this.balance -= value; }
//查询当前余额 public int getBalance(){ return this.balance; }
}
public class Demo {
public static void main(String args[]) throws InterruptedException { Bank bank = new Bank(10000); //银行的初始余额 Runnable Atm1 = () -> { bank.withdraw(5000); System.out.println("A 提款 5000"); };
Runnable Atm2 = () -> { bank.withdraw(5000); System.out.println("B 提款 5000"); };
Thread A = new Thread(Atm1); //提款人A的操作线程 Thread B = new Thread(Atm2);//提款人B的操作线程 A.start();//A开始提款 B.start();//B开始提款 A.join();//等待A操作结束 B.join();//等待B操作结束
//显示余额 System.out.println("银行余额:"+bank.getBalance()); }}
public class Bank{   //银行余额  private int balance;  private final ReentrantLock lock = new ReentrantLock();  …….   //用户提款   public void withdraw (int value)  {       lock.lock(); //加上保护锁       try {           Thread.sleep(300); //0.3秒的模拟时延       } catch (InterruptedException e) {           e.printStackTrace();       }       this.balance -= value;       lock.unlock(); //释放保护锁   }}

区块链新闻,比特币行情,比特币价格分析,数字货币新闻资讯