为什么下面例子只输出:
print
---save
---save存入2000
sleep
xingle
例子:
package zhang11_Thread;
import java.util.concurrent.locks.ReentrantLock;
public class WaitNotifyTest {
public static void main(String[] args) {
ATMZhanghu atm = new ATMZhanghu("ATM",0);
SavePerson savep = new SavePerson(atm,2000);
PrintPerson printp = new PrintPerson(atm,2000);
Thread tp = new Thread(printp,"print");
Thread ts = new Thread(savep,"---save");
tp.start();
ts.start();
}
}
class ATMZhanghu{
private final ReentrantLock lock = new ReentrantLock();
private String name;
private int money;
private boolean falg = false;
public ATMZhanghu(String name,int money){
this.money = money;
this.name = name;
}
public synchronized void PrintMon(int printm) throws InterruptedException{
if(falg == true){
if(printm <= money){
System.out.println(Thread.currentThread().getName()+"取出"+printm);
System.out.println("sleep");
// Thread.sleep(1000);
System.out.println("xingle");
money -= printm;
}else{
System.out.println("钱不够");
}
System.out.println("余额:"+ money);
falg = false;
notifyAll();
}else{
wait();
}
}
public synchronized void SaveMon(int savem) throws InterruptedException{
if(falg == true){
wait();
}else{
System.out.println(Thread.currentThread().getName()+"存入"+savem);
System.out.println("sleep");
// Thread.sleep(1000);
System.out.println("xingle");
this.money +=savem;
falg = true;
notifyAll();
}
}
public ReentrantLock getLock() {
return lock;
}
public String getName() {
return name;
}
public int getMoney() {
return money;
}
public boolean isFalg() {
return falg;
}
}
class SavePerson implements Runnable{
private ATMZhanghu atmz;
private int savem;
public SavePerson(ATMZhanghu atm,int m){
this.atmz = atm;
this.savem = m;
}
public void run(){
System.out.println(Thread.currentThread().getName() + " " );
try {
atmz.SaveMon(savem);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class PrintPerson implements Runnable{
private ATMZhanghu atmz;
private int printm;
public PrintPerson(ATMZhanghu atm,int m){
this.atmz = atm;
this.printm = m;
}
public void run(){
System.out.println(Thread.currentThread().getName() + " " );
try {
atmz.PrintMon(printm);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|