【问题标题】:Example of deadlock死锁示例
【发布时间】:2019-08-14 09:54:37
【问题描述】:

我检查了许多网站,deadlock 的唯一示例是这样的。 synchronized 块内总是有一个 synchronized 块。

(方法withdraw被a锁定,方法deposit被b锁定。)

class Account
{
    int balance;
    Account(int amount)
    {balance = amount;}

    void withdraw(int amount)
    {balance-=amount;}

    void deposit(int amount)
    {balance+=amount;}
}

class Threaddemo extends Thread
{
    Account a,b;
    int amount;

    Threaddemo(Account a,Account b,int amount)
    {
        this.a=a;this.b=b;this.amount=amount;
        start();
    }

    public void run()
    {
        transfer(a,b,amount);
    }

    public void transfer(Account a,Account b,int amount)
    {
        synchronized(a)
        {
            a.withdraw(amount);
            System.out.print(amount+" is withdrawn from account a\n");

            try{Thread.sleep(500);}
            catch(Exception e){System.out.println(e);}

            synchronized(b)
            {
                b.deposit(amount);
                System.out.print(amount+" is deposited into account b\n");
            }
        }
    }
}
class U3
{
    public static void main(String[] args) 
    {
        Account a = new Account(1000);
        Account b = new Account(2000);

        new Threaddemo(a,b,100);
        new Threaddemo(b,a,200);

    }
}

但如果我们在同步块之后使用同步块,则不会出现死锁。

class Account
{
    int balance;
    Account(int amount)
    {balance = amount;}

    void withdraw(int amount)
    {balance-=amount;}

    void deposit(int amount)
    {balance+=amount;}
}

class Threaddemo extends Thread
{
    Account a,b;
    int amount;

    Threaddemo(Account a,Account b,int amount)
    {
        this.a=a;this.b=b;this.amount=amount;
        start();
    }

    public void run()
    {
        transfer(a,b,amount);
    }

    public void transfer(Account a,Account b,int amount)
    {
        synchronized(a)
        {
            a.withdraw(amount);
            System.out.print(amount+" is withdrawn from account a\n");

            try{Thread.sleep(500);}
            catch(Exception e){System.out.println(e);}
        }
        synchronized(b)
        {
            b.deposit(amount);
            System.out.print(amount+" is deposited into account b\n");
        }
    }
}
class U3
{
    public static void main(String[] args) 
    {
        Account a = new Account(1000);
        Account b = new Account(2000);

        new Threaddemo(a,b,100);
        new Threaddemo(b,a,200);

    }
}

如果这是获得死锁的唯一方法,那么我们为什么不使用两个单独的同步块呢? 如果还有其他方法可以导致死锁,请举例说明。

【问题讨论】:

  • "为什么我们不使用两个单独的死锁"?你想如何使用死锁??
  • “为什么我们不使用两个单独的死锁”你的意思是为什么不使用两个同步块,一个接一个?是的,这是避免死锁的一种方法。
  • Oracle's Tutorial 上的示例
  • ... 在您的示例中,如果您对锁进行顺序化,您将避免死锁,但您将失去线程安全性。正确的解决方案是每个人都以相同的顺序获取锁。
  • Re,“为什么我们不使用两个单独的同步块?”因为那会破坏目的。 synchronized 的主要目的是防止任何线程在其他线程正在更改数据时看到处于不一致状态的数据。 transfer() 示例应该显示其他线程如何在事务之前或事务之后查看数据库,但绝不会在事务中间。但是两个synchronized 块之间的差距,无论多么小,都让其他线程有机会在事务仅完成一半时看到它的数据。

标签: java multithreading deadlock


【解决方案1】:

假设一家银行拥有数千个Account 类型的银行账户。现在让我们看看为什么这段代码会导致死锁:

public void transfer(Account a,Account b,int amount)
    {
        synchronized(a)
        {
            a.withdraw(amount);
            System.out.print(amount+" is withdrawn from account a\n");

            try{Thread.sleep(500);}
            catch(Exception e){System.out.println(e);}

            synchronized(b)
            {
                b.deposit(amount);
                System.out.print(amount+" is deposited into account b\n");
            }
        }
    }

让有一个线程tA和线程tB。如果线程tA 运行以下代码 transfer(accountA, AccountB) 而线程 tB 同时运行 transfer(accountB, accountA),可能会出现死锁,因为如果我们查看以下顺序:

  1. tA:synchronized(accountA)

  2. tB​​:synchronized(accountB)

  3. tA:试图锁定对象AccountB,但锁定被tB持有=> 死锁

我们看到两者之间存在循环依赖关系,不允许其中一个线程继续前进。

如果我们查看您的更新代码:

public void transfer(Account a,Account b,int amount)
    {
        synchronized(a)
        {
            a.withdraw(amount);
            System.out.print(amount+" is withdrawn from account a\n");

            try{Thread.sleep(500);}
            catch(Exception e){System.out.println(e);}
        }
        synchronized(b)
        {
            b.deposit(amount);
            System.out.print(amount+" is deposited into account b\n");
        }
    }

我们必须采取以下假设:

  • 账户 a 有无限的资金,因为它可能是 a.balance =0。

    • 我们允许不一致,例如如果我们要汇总所有当前现金,我们将汇总少于实际金额,因为您当前的代码允许我们这样做。

如果我们尝试修复代码,我们必须在更新余额之前确保 a.balance >= amount。现在让我们看看以下场景:

  1. 帐户a 拥有balance < amount

  2. 我们必须等到a.balance >= amount 才能从账户a 提款

  3. 由于我们在此线程中保持帐户a 的锁定,因此没有其他线程可以更新a.balance => 我们遭受饥饿

要解决这些问题,您要么必须使用监视器或条件来检查 a.balance>=amount 是否进行,并将线程置于阻塞状态,以便线程可以继续或更新您的代码,例如锁总是以相同的顺序获取的。

解决方案#1:获取对象锁的唯一顺序

如果我们使用唯一的顺序来获取对象的锁,我们可以确保在我们以指定的顺序获取锁时不会发生死锁,不允许任何循环依赖,否则称为死锁。

public void transfer(Account a,Account b,int amount)
    {
       //define a specific order, in which locks are acquired
       //the id's of all accounts are unique!
       if(a.id<b.id){
          synchronized(a){
            synchronized(b){
               //do operations here
            }
          }
       }else{
          synchronized(b){
            synchronized(a){
               //do operations here
            }
          }
       }
    }

解决方案 #2:使用生产者-消费者模式检查 a.balance&gt;=amount。

public void transfer(Account a,Account b,int amount)
{
    while(true){
      synchronized(a){
          if(a.balance>=amount){
              //do operations here
          }
      }

        try{Thread.sleep(500);} //Use this as a backoff, as otherwise you'd likely get high congestion
        catch(Exception e){System.out.println(e);}
    }
    synchronized(b)
    {
       //do operations here
    }
}

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 2016-07-06
    • 2021-06-25
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多