我将if条件的times设置成大于等于二,但是一般要多执行几次才会执行出show,经常不会执行show,这是怎么回事啊?
public class TestBank {
public static void main(String[] args) {
new TestBank().run();
}
public void run() {
Family f = new Family();
new Thread(f,"丈夫").start();
new Thread(f,"妻子").start();
while(true){
if(f.times>=2) {
f.show();
break;
}
}
}
class Family implements Runnable {
private int saveMoney;
private int getMoney;
private int curMoney;
private volatile int times = 0;
public Family() {
saveMoney = 5000;
getMoney = 2000;
curMoney = 0;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"取了:"+getMoney+"元");
curMoney+=getMoney;
int temp = saveMoney - getMoney;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
saveMoney = temp;
times++;
}
public void show() {
System.out.println("银行还有:"+saveMoney+",家里中有:"+curMoney);
}
}
}