2012-02-05 63 views
0

我試圖在Bank.transfer使用​​和ReentrantLock,但我得到的輸出是這樣的:「從7至3轉移82.0共計918」我同步不起作用

,「從0到4轉移27.0。總計973「

雖然Total必須等於1000.告訴我我錯了什麼?

public class expr { 
    public static Bank b = new Bank(); 
    public static void main(String[] args) throws IOException, InterruptedException { 
     for (int i = 0; i < 4; i++) { 
      new BankTransfer(); 
     } 
    } 
} 

public class BankTransfer implements Runnable{ 

    public BankTransfer() { 
     Thread t = new Thread(this); 
     t.start(); 
    } 

    @Override 
    public void run() { 

     while (true){ 
      int from = (int) (expr.b.size * Math.random()); 
      int to = (int) (expr.b.size * Math.random()); 
      int amount = (int) (100 * Math.random()); 
      expr.b.transfer(from, to, amount); 

      try { 
       Thread.sleep((long) (2000 * Math.random())); 
      } catch (InterruptedException e) { 
       System.out.println("Thread was interrupted!"); 
       return; 
      } 

     } 
    } 


} 

public class Bank { 
    private int[] accounts; 
    public int size = 10; 
    private Lock block = new ReentrantLock(); 
    public boolean transfer(int from, int to, double amount){ 
     block.lock(); 
     try{ 
      if(accounts[from] >= amount && from != to){ 
       accounts[from] -= amount; 
       System.out.println("From " + from + " to " + to + " transfered " + amount + ". Total " + getTotal()); 
       accounts[to] += amount; 
       return true; 
      } 
     }finally { 
      block.unlock(); 
     } 
     return false; 
    } 
    public Bank(){ 
     accounts = new int[size]; 
     for (int i = 0; i < size; ++i) { 
      accounts[i] = 100; 
     } 
    } 
    private int getTotal(){ 
     int sum = 0; 
     for (int i = 0; i < size; ++i) sum += accounts[i]; 
     return sum; 
    } 
} 
+3

「選擇沒有損壞」。請記住這句話,意思是說,如果一個建立良好的語言的基本部分不適合你,那可能就是你在做什麼。 – 2012-02-05 20:23:58

+5

同步在Java中完美運行。 [第一編程規則:它總是你的錯](http://www.codinghorror.com/blog/2008/03/the-first-rule-of-programming-its-always-your-fault.html) – 2012-02-05 20:24:01

+0

有看你在哪裏打印輸出。 – bdecaf 2012-02-05 20:31:30

回答

3

計算完成後,您完成transfier的兩端...即移動帳戶[到] + =金額後的System.println。

+0

哦,當然。我需要睡覺:( – user1003208 2012-02-05 20:31:05

1

這部分看起來很奇怪:

accounts[from] -= amount; 
System.out.println("From " + from + " to " + to + " transfered " + amount + ". Total " + getTotal()); 
accounts[to] += amount; 

你之前打印的總傳輸完成。

1

您在從一個帳戶中扣除資金後打電話給getTotal(),但是之前將其添加到另一個帳戶。它將始終顯示少於100,按轉移的金額。