问题:每次先存一次钱,然后再取一次钱。 两个线程交替进行。
方式一:使用 同步监视器 对象的等待 wait方法 和 唤醒 notifyAll方式 来实现。
1. 定义falg 标签 来标记 应该取钱还是存钱。开始为false , 表示先存钱
2.每次操作时,进行判断,取钱应该满足 falg = true , 存钱应该满足 falg = false; 要用while 进行判断!! 不要用if - else 。
我在其他书上看到了 if - else 的形式, 这样条件为 false --> wait -> notify ->方法结束 。
使用while时, 条件为false -> wait -> notify -> 重新判断条件 -- 这样线程数量不会减少。
package synchronizedxx;
public class Account {
private String accountNo;
private double balance;
private boolean falg = false;
public Account(String accountNo,double balance){
this.accountNo = accountNo;
this.balance = balance;
}
public synchronized void draw(double drawAmont){
try {
while (!falg)
wait();
{
System.out.println(Thread.currentThread().getName()+ " 取钱:"+drawAmont);
falg = !falg;
balance -= drawAmont;
System.out.println("余额为:"+balance);
notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void deposit(double drawAmont){
try {
while (falg)
wait();
{
System.out.println(Thread.currentThread().getName()+ " 存钱:"+drawAmont);
falg = !falg;
balance -= drawAmont;
System.out.println("余额为:"+balance);
notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package synchronizedxx;
public class DrawThread extends Thread{
private Account account;
private double drawAmont;
public DrawThread(String name,Account account,double drawAmont) {
super(name);
this.account = account;
this.drawAmont = drawAmont ;
}
@Override
public void run() {
for (int i=0;i<10;i++){
System.out.println("draw:"+i);
account.draw(drawAmont);
}
}
}
package synchronizedxx;
public class DepositThread extends Thread{
private Account account;
private double depositAmont;
public DepositThread(String name,Account account,double depositAmont) {
super(name);
this.account = account;
this.depositAmont = depositAmont ;
}
@Override
public void run() {
for (int i=0;i<10;i++){
System.out.println("deposit:"+i);
account.deposit(depositAmont);
}
}
}
package synchronizedxx;
public class DrawTest {
public static void main(String[] args) {
Account account = new Account("123456",0);
new DrawThread("取钱者", account, 800).start();
new DepositThread("存钱者",account,800).start();
}
}