Java for newbies - DeadLock模仿

dan*_*nik 5 java concurrency multithreading deadlock

我正在尝试编写一个非常简单的程序,它将模仿简单的DeadLock,其中线程A等待由线程B锁定的资源A,线程B等待由线程A锁定的资源B.

这是我的代码:

//it will be my Shared resource
public class Account {
    private float amount;

    public void debit(double amount){
        this.amount-=amount;
    }

    public void credit(double amount){
        this.amount+=amount;
    }

}  
Run Code Online (Sandbox Code Playgroud)

这是我的runnable,它在上面的资源上执行Operation:

public class BankTransaction implements Runnable {
    Account fromAccount,toAccount;
    float ammount;
    public BankTransaction(Account fromAccount, Account toAccount,float ammount){
        this.fromAccount = fromAccount;
        this.toAccount = toAccount;
        this.ammount = ammount;
    }

    private void transferMoney(){
        synchronized(fromAccount){
            synchronized(toAccount){
                fromAccount.debit(ammount);
                toAccount.credit(ammount);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                e.printStackTrace();
                }
                System.out.println("Current Transaction Completed!!!");
            }
        }
    }

    @Override
    public void run() {
        transferMoney();
    }

}
Run Code Online (Sandbox Code Playgroud)

最后我的主要课程:

    public static void main(String[] args) {

    Account a = new Account();
    Account b = new Account();
    Thread thread1 = new Thread(new BankTransaction(a,b,500));

    Thread thread2 = new Thread(new BankTransaction(b,a,500));
       thread1.start();  
       thread2.start();  
System.out.println("Transactions Completed!!!");

    }
}
Run Code Online (Sandbox Code Playgroud)

为什么这个代码运行成功,我没有和deadLock?

Jon*_*eet 10

它有可能发生死锁 - 但是两个锁都是如此快速地获得的,以至于一个线程可以在另一个线程获得第一个之前获得两个锁.

Thread.sleep(500);在两个同步语句之间进行另一次调用,它会发生死锁:两个线程都会进入"他们的"外部锁定,睡眠,然后当他们醒来时,他们都会发现他们已经获得了他们的"内部"锁定.

这是因为你的synchronized语句是反对称的:对于一个线程,外部同步锁是另一个线程的内部同步锁,反之亦然.


Oli*_*rth 5

其中一个线程可能会进入两个 synchronized部分,完全阻塞另一个线程直到完成.