黑马程序员技术交流社区
标题:
两个线程间的交替执行
[打印本页]
作者:
GXM
时间:
2016-11-2 20:55
标题:
两个线程间的交替执行
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();
}
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2