package java_learning;
/*定义一个Account类,这个类中有取钱和存钱的两个方法*/
class Account{
private String m_accountNo;
private double m_balance;
// 是否有钱
private boolean m_flag = false;
public Account(){
super();
}
public Account(String accountNo, double balance){
super();
this.m_accountNo = accountNo;
this.m_balance = balance;
}
public synchronized void draw(double drawAmount){ //取钱
try{
if (!m_flag){//没钱
this.wait();
}else{
//取钱
System.out.println(Thread.currentThread().getName()+"取钱"+drawAmount);
m_balance= m_balance-drawAmount;
System.out.println("余额 : "+ m_balance);
//将标识账户是否已有存款的标志设为false
m_flag=false;
//唤醒其它线程
this.notifyAll();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void deposit(double depositAmount){ //存钱
try {
if(m_flag){
this.wait();
}
else{
System.out.println(Thread.currentThread().getName()+"存钱"+depositAmount);
m_balance = m_balance+depositAmount;
System.out.println("账户余额为:"+m_balance);
m_flag = true;
//唤醒其它线程
this.notifyAll();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
class DrawThread implements Runnable {
private Account account;
private double drawAmount;
public DrawThread(Account account, double drawAmount) {
super();
this.account = account;
this.drawAmount = drawAmount;
}
public void run() {
for(int i=0;i<100;i++){
account.draw(drawAmount);
}
}
}
class depositThread implements Runnable{
private Account account;
private double depositAmount;
public depositThread(Account account, double depositAmount) {
super();
this.account = account;
this.depositAmount = depositAmount;
}
public void run() {
for(int i=0;i<100;i++){
account.deposit(depositAmount);
}
}
}
public class TestDraw {
public static void main(String[] args) {
//创建一个账户
Account account=new Account();
new Thread(new DrawThread(account, 800),"取钱者 1 ").start();
new Thread(new DrawThread(account, 800),"取钱者 2 ").start();
new Thread(new DrawThread(account, 800),"取钱者 3 ").start();
new Thread(new DrawThread(account, 800),"取钱者 4 ").start();
//new Thread(new depositThread(account, 800),"存款者 甲 ").start();
//new Thread(new depositThread(account, 800),"存款者 乙 ").start();
//new Thread(new depositThread(account, 800),"存款者 丙 ").start();
new Thread(new depositThread(account, 800),"存款者 wangry ").start();
}
}
/*wait( ) 告知被调用的线程放弃管程进入睡眠直到其他线程进入相同管程并且调用notify( )。
• notify( ) 恢复相同对象中第一个调用 wait( ) 的线程。
• notifyAll( ) 恢复相同对象中所有调用 wait( ) 的线程。具有最高优先级的线程最先运行。
*/
TestDraw
最新推荐文章于 2019-02-17 15:22:37 发布