銀行卡賬戶入賬支出問題

中都發表於2018-09-16

問題: 1、一個銀行卡賬戶,一個執行緒實現每5s扣除1200元; 2、一個執行緒實現每3s入賬100元; 3、銀行卡本身每2s入賬200元;

程式碼:

/**
 * @author lzq
 *
 */

class ZhangHu {
	private int number = 0;
	
	public synchronized void get(int x) {
		if(number < x) {
			System.out.println("餘額不足");
			return;
		}
		number = number-x;
		System.out.println("出賬"+x+"; 餘額"+number);
	}
	
	public synchronized void put(int x) {
		number = number+x;
		System.out.println("入賬"+x+"; 餘額"+number);
	}
}

class XiangChen1 extends Thread {
	ZhangHu zh;
	
	public XiangChen1(ZhangHu zh) {
		this.zh = zh;
	}
	
	public void run() {
		while(true) {
		try {
			Thread.sleep(3000);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		zh.put(100);
		}
	}
}


class XiangChen2 extends Thread {
	ZhangHu zh;
	
	public XiangChen2(ZhangHu zh) {
		this.zh = zh;
	}
	
	public void run() {
		while(true) {
		try {
			Thread.sleep(5000);
		}catch(InterruptedException e) {
			e.printStackTrace();
		}
		zh.get(1200);
		}
	}
}

public class TestDemo15 {
	
	public static void main(String[] args) {
		ZhangHu y = new ZhangHu();
		XiangChen1 x1 = new XiangChen1(y);
		XiangChen2 x2 = new XiangChen2(y);
		
		x1.start();
		x2.start();
		
		while(true) {
			try {
				Thread.sleep(2000);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
			y.put(200);
		}
	}

}

執行結果:

入賬200; 餘額200
入賬100; 餘額300
入賬200; 餘額500
餘額不足
入賬200; 餘額700
入賬100; 餘額800
入賬200; 餘額1000
入賬100; 餘額1100
入賬200; 餘額1300
出賬1200; 餘額100
入賬200; 餘額300
入賬100; 餘額400
入賬200; 餘額600
餘額不足
入賬100; 餘額700
入賬200; 餘額900
入賬100; 餘額1000
入賬200; 餘額1200
出賬1200; 餘額0
入賬200; 餘額200
入賬100; 餘額300
入賬200; 餘額500
入賬100; 餘額600
入賬200; 餘額800

相關文章