我检查了很多网站,唯一的例子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);
}
}
但是如果我们在一个同步块之后使用一个同步块,就不会有死锁。
如果这是导致死锁的唯一方法,那我们为什么不使用两个单独的同步块呢?如果还有其他方法导致死锁,请举例说明。
江户川乱折腾
相关分类