Skip to content

Latest commit

 

History

History
66 lines (45 loc) · 1.03 KB

多線程安全示例.md

File metadata and controls

66 lines (45 loc) · 1.03 KB

多線程安全示例

需求: 兩個儲戶,每個都到銀行存錢,每次存100,共存三次。

Example

public class Customer implements Runnable {//多個儲戶

	private Bank b = new Bank();//實例化對象並共享數據
	
	public void run() {
		
		for(int i = 0; i < 3; i++) {//存款次數
			
			b.add(100);
		}
	}
}

public class Bank {
	
	private int sum;//金庫金額
//	private  Object obj = new Object();//共用對象
	
	public synchronized void add(int num) {//同步函數
		
//		synchronized(obj) {//同步代碼塊
			
			sum += num;//金額變化
			
						try {
				
				Thread.sleep(10);//釋放執行權
			} catch(InterruptedException e) {
			
			}
			
			System.out.println("Money = " + sum);
//		}
	}
}

public class BankDemo {

	public static void main(String[] args) {
		
		Customer c = new Customer();
		
		Thread t1 = new Thread(c);
		Thread t2 = new Thread(c);
		
		t1.start();
		t2.start();
	}
}

打印結果

Money = 100
Money = 200
Money = 300
Money = 400
Money = 500
Money = 600