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();
}
}