①Inheritance (extends Thread)
package testSingleton; public class TestAccount { public static void main(String[] args) { Account acct = new Account(); Customer c1 = new Customer(acct); Customer c2 = new Customer(acct); c1.setName("甲"); c2.setName("乙"); c1.start(); c2.start(); } } class Account{ double balance; //余额 public Account() { } // deposit money public synchronized void deposit( double amt) { balance + = amt; try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" + balance); } } class Customer extends Thread{ Account account; public Customer(Account account) { this.account = account; } public void run() { for(int i =0;i<3;i++) { account.deposit(1000); } } }
② Implementation (implements Runnable)
package testSingleton; public class TestAccount2 { public static void main(String[] args) { Account1 accc = new Account1(); Customer1 c1 = new Customer1(accc); Customer1 c2 = new Customer1(accc); Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); t1.setName( "Guo Hao" ); t2.setName( "window" ); t1.start(); t2.start(); } } class Account1{ double balance; public Account1(){ } // Save money public synchronized void depsoit( double e){ balance+=e; System.out.println(Thread.currentThread().getName()+":"+balance); } } class Customer1 implements Runnable{ Account1 account; public Customer1(Account1 acc) { this.account = acc; } @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<3;i++) { account.depsoit(1000); } } }