今天在JavaWorld.tw论坛上看到一个求提款和存款的帖子(http://www.javaworld.com.tw/jute/post/view?bid=29&id=247594&sty=1&tpg=1&age=0),自己写了个例子,加深对Java Thread的学习和理解:
package cn.xbmu.lib.jfly.test;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A:帳戶類別:
設計提款功能,每次可以提出100元,但是當帳戶餘額為0,不可以再提款。
設計存款功能,每次可以存入1000元,但是當帳戶餘額不為0,不可以再存款。
B:提款類別:在此類別中執行「提款」的功能。
C:存款類別:在此類別中執行「存款」的功能。
D:主程是要啟動使用「提款類別」和「存款類別」兩個執行緒。
* @author JFly
*/
public class MySaveAndGet {
public static void main(String[] args) throws InterruptedException {
Account acc = new Account();
PutMoney pm = new PutMoney(acc);
TakeMoney tm = new TakeMoney(acc);
pm.start();
tm.start();
Thread.sleep(5000); // 模拟动作执行5秒
synchronized(pm) {
pm.close = true;
pm.notifyAll();
}
synchronized(tm) {
tm.close = true;
tm.notifyAll();
}
}
}
class Account {
int m; // 帐户余额
boolean t_or_p = false; // 提款或者存款,false存款,true提款
void takeM() {
if (m == 0) {
System.out.println("帐户余额为0,不可以再提款!");
} else {
m = m - 100;
System.out.println("取出后剩余 " + m);
}
t_or_p = true; // 提款动作
}
void putM() {
if (m != 0) {
System.out.println("帐户余额不为0,不可以再存款!");
} else {
m = m + 1000;
System.out.println("存入后剩余 " + m);
}
t_or_p = false; // 存款动作
}
}
class PutMoney extends Thread {
Account acc = null;
boolean close = false;
public PutMoney(Account acc) {
this.acc = acc;
}
@Override
public void run() {
while (true) { // 模拟存款
synchronized (acc) {
while (!acc.t_or_p) {
try {
acc.wait();
} catch (InterruptedException ex) {
Logger.getLogger(PutMoney.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(close) {
break;
}
acc.putM();
acc.notifyAll();
}
}
}
}
class TakeMoney extends Thread {
Account acc = null;
boolean close = false;
public TakeMoney(Account acc) {
this.acc = acc;
}
@Override
public void run() {
while (true) { // 模拟提款
synchronized (acc) {
while (acc.t_or_p) {
try {
acc.wait();
} catch (InterruptedException ex) {
Logger.getLogger(TakeMoney.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(close) {
break;
}
acc.takeM();
acc.notifyAll();
}
}
}
}