一文读懂Java多线程背后的故事

  public class BankAccount {

  private int balance;

  public synchronized void deposit(int amount) {

  balance += amount;

  }

  public synchronized void withdraw(int amount) {

  balance -= amount;

  }

  public synchronized int getBalance() {

  return balance;

  }

  }

  public class TransferTask implements Runnable {

  private final BankAccount sourceAccount;

  private final BankAccount targetAccount;

  private final int amount;

  public TransferTask(BankAccount sourceAccount, BankAccount targetAccount, int amount) {

  this.sourceAccount = sourceAccount;

  this.targetAccount = targetAccount;

  this.amount = amount;

  }

  @Override

  public void run() {

  sourceAccount.withdraw(amount);

  targetAccount.deposit(amount);

  }

  }

  public class BankExample {

  public static void main(String[] args) {

  BankAccount account1 = new BankAccount();

  BankAccount account2 = new BankAccount();

  account1.deposit(1000);

  TransferTask transferTask1 = new TransferTask(account1, account2, 500);

  TransferTask transferTask2 = new TransferTask(account2, account1, 300);

  Thread thread1 = new Thread(transferTask1);

  Thread thread2 = new Thread(transferTask2);

  thread1.start();

  thread2.start();

  try {

  thread1.join();

  thread2.join();

  } catch (InterruptedException e) {

  e.printStackTrace();

  }

  System.out.println("Account 1 balance: " + account1.getBalance());

  System.out.println("Account 2 balance: " + account2.getBalance());

  }

  }