簡體   English   中英

多個線程共享同一對象的Java同步問題

[英]Java Synchronization issue with muliple threads sharing same object

我目前正在學習Java中的同步。 據我了解,同步實例方法獲得了對其對象的鎖定。

我的程序是在其中執行50個任務,然后為每個任務分配一個線程。 每個任務都會向由Account Class制成的Account對象添加一分錢。

帳戶類具有余額數據字段和用於存儲的同步方法。 這50個任務有一個帳戶字段,該字段將指向同一帳戶對象(即共享帳戶)。 一旦運行被調用,每個任務將調用account.deposit實例方法來存儲1個單位。

我希望余額以50個單位結束。 令人驚訝的是,該帳戶有時結余50或其他余額14、48、33等。

class JavaStudy {
    public static void main(String[] args){

        for (int j = 0; j < 10; j++) {

            Account account = new Account();

            ExecutorService executorPool = Executors.newFixedThreadPool(50);

            for (int i = 0; i < 50; i++) {
                executorPool.execute(new DepositTask(account));
            }

            executorPool.shutdown();

            while(!executorPool.isShutdown()){
            }

            System.out.println(account.getBalance());
        }
    }
}

存款任務類!

class DepositTask implements Runnable {

    private Account account;

    DepositTask(Account account){
       this.account = account;
  }

   @Override
  public void run() {
       account.deposit(1);
  }
}

帳戶類別!

class Account {

    private int balance = 0;

    synchronized public void deposit(int amount){
        int balance = this.balance + amount;
        this.balance = balance;
    }

    String getBalance(){
        return "Balance: " + balance;
    }
}

根據我的理解,一旦任務訪問account.deposit(1);就應該鎖定該帳戶。 。其他任務應該無法訪問它,因為它們共享同一個對象! 不知何故,我最終得到下面的結果,

Balance: 20
Balance: 47
Balance: 50
Balance: 42
Balance: 27
Balance: 24
Balance: 50
Balance: 29
Balance: 13
Balance: 12

Process finished with exit code 0

有什么想法嗎?

我懷疑您不是在等待終止,這與關機不同。 這可能意味着並非所有任務都已執行。

executorPool.shutdown();
executorPool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println(account.getBalance());

順便說一句,在Java 8中,您可以使用

Account account = new Account();

InStream.range(0, 50).parallel()
                     .forEach(i -> account.deposit(1));

System.out.println(account.getBalance());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM