public class Test1 {
public static void main(String[] args) {
Account acct = new Account();
Customer c1 = new Customer(acct);
Customer c2 = new Customer(acct);
Thread t1 = new Thread(c1, "AA");
Thread t2 = new Thread(c2, "BB");
t1.start();
t2.start();
}
}
class Account {
double balance;
public synchronized void deposite(double amt) throws InterruptedException {
notify(); //实现通信用通信的方法
balance += amt;
System.out.println(Thread.currentThread().getName() + ":余额为" + balance);
wait(); //实现交互打印
}
}
class Customer implements Runnable {
Account account;
public Customer(Account account) {
super();
this.account = account;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
account.deposite(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} |
|