package com.ibeidou.thread;
/**
* 测试wait和notify方法
* 两个线程操作同一对象,一个线程调用wait方法,另一个之后调用notify方法
* 等待是当前线程对对象等待,唤醒是线程对等待对象的所有线程唤醒(可随机唤醒一个,可唤醒所有的)
* @author sam 2012-4-11
*/
public class TestWaitAndNotify {
Account account = new Account("Boy",100d);
class Account{
String name;
double balance;
Account(String name, double balance){
this.name = name;
this.balance = balance;
}
void deposit(double money){
System.out.println("Before deposit balance is " + balance);
this.balance += money;
System.out.println("After deposit balance is " + balance);
}
void withdraw(double money){
System.out.println("Before withdraw balance is " + balance);
this.balance -= money;
System.out.println("After withdraw balance is " + balance);
}
}
class BoyThread extends Thread{
@Override
public void run(){
for(int i = 0; i < 10; i++){
synchronized (account){
account.deposit(10d);
//随机唤醒一个等待account的线程
account.notify();
//唤醒所有等待account的线程
//account.notifyAll();
}
}
}
}
class GirlThread extends Thread{
@Override
public void run(){
try{
for(int i = 0; i < 10; i++){
synchronized (account){
//总是需要判断余额,因为当线程被唤醒时,有可能余额不足0
while(account.balance <= 0){
//当前线程开始等待account对象
account.wait();
}
account.withdraw(50d);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
void testWaitAndNotify(){
BoyThread boy = new BoyThread();
GirlThread girl = new GirlThread();
boy.start();
girl.start();
}
public static void main(String[] args){
TestWaitAndNotify twan = new TestWaitAndNotify();
twan.testWaitAndNotify();
}
}