Java開發中多線程同步技巧
|
在編寫一個類時,如果該類中的代碼可能運行于多線程環境下,那么就要考慮同步的問題。在Java中內置了語言級的同步原語--synchronized,這也大大簡化了Java中多線程同步的使用。 我們首先編寫一個非常簡單的多線程的程序,是模擬銀行中的多個線程同時對同一個儲蓄賬戶進行存款、取款操作的。
在程序中我們使用了一個簡化版本的Account類,代表了一個銀行賬戶的信息。在主程序中我們首先生成了1000個線程,然后啟動它們,每一個線程都對John的賬戶進行存100元,然后馬上又取出100元。這樣,對于John的賬戶來說,最終賬戶的余額應該是還是1000元才對。然而運行的結果卻超出我們的想像,首先來看看我們的演示代碼:
class Account { String name; float amount; public Account(String name, float amount) { this.name = name; this.amount = amount; } public void deposit(float amt) { float tmp = amount; tmp += amt; try { Thread.sleep(100); //模擬其它處理所需要的時間,比如刷新數據庫等 } catch (InterruptedException e) { // ignore } amount = tmp; } public void withdraw(float amt) { float tmp = amount; tmp -= amt; try { Thread.sleep(100); //模擬其它處理所需要的時間,比如刷新數據庫等 } catch (InterruptedException e) { // ignore } amount = tmp; } public float getBalance() { return amount; } } public class AccountTest { private static int NUM_OF_THREAD = 1000; static Thread[] threads = new Thread[NUM_OF_THREAD]; public static void main(String[] args) { final Account acc = new Account("John", 1000.0f); for (int i = 0; i< NUM_OF_THREAD; i++) { threads[i] = new Thread(new Runnable() { public void run() { acc.deposit(100.0f); acc.withdraw(100.0f); } } ); threads[i].start(); } for (int i=0; i<NUM_OF_THREAD; i++) { try { threads[i].join(); //等待所有線程運行結束 } catch (InterruptedException e) { // ignore } } System.out.println("Finally, John's balance is:" + acc.getBalance()); }} |