3
回答
求助个Java多线程的问题
滴滴云服务器,限时包月0.9元,为开发者而生>>>   
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循环内添加一条输出语句,程序也是正常的,求解是什么问题



举报
rubyroes
发帖于2年前 3回/158阅
顶部