2012-10-01 75 views
1

我正在嘗試多線程銀行轉賬問題。但是,我遇到了正確同步線程的問題。定期在線程執行賬戶之間的轉賬後,它將進行測試以確保沒有錢獲得或完全損失。Java多線程銀行轉賬,同步問題

當一個線程進入測試方法時,它應該設置一個標誌,以防止任何其他線程進入傳輸方法,然後等待所有當前正在執行的線程傳輸結束。

public void transfer(int from, int to, int amount) {   
    //finish running all threads' current transactions before test 

    accounts[from].waitForAvailableFunds(amount); 
    if (!open) return;  

    //checks to see if any thread is currently testing 
    //if so, wait 
    while(flag) { 
     try { 
      wait(); 
     } catch (InterruptedException e) { /*ignore*/ } 
    } 

    //do not execute these two statements when a thread 
    //is performing a test 
    if (accounts[from].withdraw(amount)) { 
     accounts[to].deposit(amount); 

    } 

    if (shouldTest() && !flag) test(); 

} 

//only one thread can perform a test at any given moment 
public synchronized void test() {   

    //when test starts set a flag telling threads to 
    //not begin any new transfers 
    flag = true; 

    //wait for all threads currently performing transfers 
    //to finish current transfer before continuing 


    int sum = 0; 
    for (int i = 0; i < accounts.length; i++) { 
     System.out.printf("%s %s%n", 
       Thread.currentThread().toString(),accounts[i].toString()); 
     sum += accounts[i].getBalance(); 
    } 
    System.out.println(Thread.currentThread().toString() + 
      " Sum: " + sum); 
    if (sum != numAccounts * initialBalance) { 
     System.out.println(Thread.currentThread().toString() + 
       " Money was gained or lost"); 
     System.exit(1); 
    } else { 
     System.out.println(Thread.currentThread().toString() + 
       " The bank is in balance"); 
    } 

    //reset flag and notify threads test is complete. 
    flag = false; 
    notifyAll(); 
} 

首先,我甚至不積極我已經設置了標誌並正確等待。其次,如何讓進入測試方法的線程等待所有其他正在執行傳輸的線程完成當前傳輸。

感謝

回答

0

我認爲你應該使用揮發性裝飾標誌,以確保當它在不同的線程發生變化,也受到影響。