我将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);
}
}
}
你的times++线程不安全啊,有可能最终的执行结果为times=1;
这里你可以选择使用AtomicInteger(在包java.util.concurrent.atomic下)
如: private AtomicInteger times = new AtomicInteger(0);
times++;改成times.incrementAndGet();
判断那里改成f.times.get()>=2
atomic包下的这些都是原子性操作的
希望可以帮到你...