开发者社区> 问答> 正文

求助个Java多线程的问题

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循环内添加一条输出语句,程序也是正常的,求解是什么问题

展开
收起
爵霸 2016-05-31 08:52:03 2270 0
1 条回答
写回答
取消 提交回答
  • times++; 并不是线程安全的,按照上面两个线程并发执行,你可能永远无法得到一个正确的值。

    可以使用 AtomicInteger ,然后就不会上述问题了。

    2019-07-17 19:21:13
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载