public class ThreadDemo {
public static void main(String[] args) {
new ThreadDemo().run();
}
public void run() {
Family f = new Family();
new Thread(f, "qizi").start();
new Thread(f, "zhangfu").start();
while (true) {
if (f.getTimes() >= 2) {
f.show();
break;
}
}
f.show();
}
class Family implements Runnable {
private int saveMoney;
private int getMoney;
private int curMoney;// 当前取的钱
private int times = 0;
public Family() {
saveMoney = 10000;
getMoney = 2000;
curMoney = 0;
}
public int getTimes() {
return times;
}
@Override
public void run() {
// TODO Auto-generated method stub
getMoney();
}
// 同步方法,默认使用this作为钥匙
public synchronized void getMoney() {
System.out.println(Thread.currentThread().getName() + "qule" + getMoney);
curMoney += getMoney;
int temp = saveMoney - getMoney;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
saveMoney = temp;
times++;
//System.out.println(times);
}
public void show() {
System.out.println("yinhanghaiyou" + saveMoney + "jialihaiyou" + curMoney);
}
}
}
正常运行的时候会卡死在while循环那里,Debug模式下正常,如果在while循环内添加一条输出语句,程序也是正常的,求解是什么问题
times++; 并不是线程安全的,按照上面两个线程并发执行,你可能永远无法得到一个正确的值。
可以使用 AtomicInteger ,然后就不会上述问题了。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。