Java多线程-同步函数

需求:

储户2个,每个到银行存钱,每次存100,共存三次。

BankDemo.java

 

class Bank {
   private int sum = 0;
   public synchronized void add(int num) {
      // synchronized(Bank.class)
      // {
      sum += num;
      try {
        Thread.sleep(10);
      } catch (Exception e) {
      }
      System.out.println("sum=" + sum);
      // }
   }
}

class Cus implements Runnable { Bank b = new Bank();
   public void run() {
      for (int i = 0; i < 3; i++) {
        b.add(100);
      }
   }
}

class BankDemo {

   public static void main(String[] args) {
      Cus c = new Cus();
      Thread t1 = new Thread(c);
      Thread t2 = new Thread(c);
      t1.start();
      t2.start();
   }
}