package lianxi1; class User implements Runnable{ static Account account = new Account(); @Override public void run() { for(int i=0;i<3;i++){ account.deposit(1000.00); } } } class Account{ private double balance; public Account(){ } public Account(double balance) { super(); this.balance = balance; } public synchronized void deposit(double num){ try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } balance = balance + num; //两个线程先后唤醒,第一个线程加1000,没打印,第二个线程又加1000, //开始打印第一个线程和第二个,所以线程1和2的余额相同 System.out.println(Thread.currentThread().getName()+"存款,账户余额:"+balance); } } public class TestThreadAccount { public static void main(String[] args) { User au = new User(); Thread t1 = new Thread(au); Thread t2 = new Thread(au); t1.setName("顾客1"); t2.setName("顾客2"); t1.start(); t2.start(); } }