Я пытаюсь написать очень простую программу, которая будет имитировать простую DeadLock, где поток A ожидает ресурса A, заблокированного потоком B, а поток B ожидает, что ресурс B заблокирован потоком A.
Вот мой код:
//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;
}
}
Это мой runnable, который выполняет операцию над ресурсом выше:
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();
}
}
и, наконец, мой основной класс:
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!!!");
}
}
Почему этот код выполняется успешно, а у меня нет и мертв Заблокировать?