await(),notify()是java Object类的方法.在两个线程同时访问一个对象的时候可以利用这2个方法实现线程的通信.看下面的例子.
public class Account {
private String accountNo;
private double balance;
private boolean flag = false;
public Account() {
}
public Account(String accountNo, double balance) {
this.accountNo = accountNo;
this.balance = balance;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getAccountNo() {
return this.accountNo;
}
public double getBalance() {
return this.balance;
}
public synchronized void draw(double drawAmount) {
try {
//如果flag为假,表明账户中还没有人存钱进去,则取钱方法阻塞
if (!flag) {
wait();
} else {
System.out.println(Thread.currentThread().getName() +
" 取钱:" + drawAmount);
balance -= drawAmount;
System.out.println("账户余额为:" + balance);
//将标识账户是否已有存款的旗标设为false。
flag = false;
notify();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public synchronized void deposit(double depositAmount) {
try {
//如果flag为真,表明账户中已有人存钱进去,则存钱方法阻塞
if (flag) {
wait();
} else {
//执行存款
System.out.println(Thread.currentThread().getName() +
" 存款:" + depositAmount);
balance += depositAmount;
System.out.println("账户余额为:" + balance);
//将表示账户是否已有存款的旗标设为true
flag = true;
//唤醒其他线程
notify();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public class DepositThread extends Thread {
private Account account;
private double depositAmount;
public DepositThread(String name, Account account,
double depositAmount) {
super(name);
this.account = account;
this.depositAmount = depositAmount;
}
public void run() {
for (int i = 0; i < 100; i++) {
account.deposit(depositAmount);
}
}
}
public class DrawThread extends Thread {
private Account account;
private double drawAmount;
public DrawThread(String name, Account account,
double drawAmount) {
super(name);
this.account = account;
this.drawAmount = drawAmount;
}
public void run() {
for (int i = 0; i < 100; i++) {
account.draw(drawAmount);
}
}
}
public class TestDraw {
public static void main(String[] args) {
Account acct = new Account("1234567", 0);
new DrawThread("取钱者", acct, 800).start();
new DepositThread("存款者甲", acct, 800).start();
}
}
DepositThread线程负责存钱,DrawThread线程负责取钱.flag为true时表示有钱,DepositThread线程调用await实现等待.flag为false时表示没有钱,DrawThread线程调用await实现等待.当flag为true时DrawThread实现取钱,之后调用notify(),通知DepositThread可以来存钱.当flag为false时DepositThread实现存钱,之后调用notify(),通知DrawThread可以来存钱.