u013614197
圆周率_
2016-03-04 11:52

求助个Java多线程的demo问题

  • 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;
        }
    }

}



class Family implements Runnable {
    private int saveMoney;
    private int getMoney;
    private int curMoney;// 当前取的钱
    private int times = 0;

    // 可以直接创建一个对象来作为同步锁的钥匙
    Object key = new Object();

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

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐