我正在尝试写一个非常简单的程序,它将模仿简单的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!!!");
}
}为什么这段代码运行成功,而我没有和deadLock?
发布于 2011-08-24 06:40:42
它有可能出现死锁--但是这两个锁在一起获取的速度是如此之快,以至于一个线程在另一个线程有机会获得第一个锁之前就可以同时获得这两个锁。
在两个同步语句之间放入另一个Thread.sleep(500);调用,它就会发生死锁:两个线程都会进入“它们的”外锁,进入睡眠状态,然后当它们醒来时,它们都会发现它们的“内部”锁已经被获取了。
这是因为您同步的语句是不对称的:对于一个线程,外部同步锁是另一个线程的内部锁,反之亦然。
发布于 2011-08-24 06:38:52
有可能其中一个线程会进入两个synchronized部分,完全阻塞另一个线程,直到它完成为止。
发布于 2011-08-24 06:42:06
你需要模拟“不幸的时机”。尝试在两个锁之间添加睡眠:
synchronized(fromAccount){
Thread.sleep(2000);
synchronized(toAccount){https://stackoverflow.com/questions/7168347
复制相似问题