我试图写的很简单的程序,它会模仿简单的僵局,在那里线程A用于资源A的锁定等待由线程B和线程B等待资源B线程A锁定Java的新手 - 死锁仿
这里是我的代码:
//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;
}
}
这是我可以运行它上面的资源上进行操作:
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!!!");
}
}
为什么此代码运行成功执行,我没有和deadLock?
睡眠可以引入非确定性。你可以使它具有确定性;请参阅下面的答案。 – Toby
@Toby:是的,你可以使它成为确定性的 - 但是'sleep'是显示死锁*可能发生的一种好方法,因为你总能想象一个没有睡眠的程序执行类似于*使用睡眠的程序,只是凭借未安排的线程。换句话说,当你插入睡眠时失败的程序本质上是有缺陷的,因为你可能在现实生活中看到“意外”的相同。插入通知也是如此。 –