【发布时间】:2019-08-14 09:54:37
【问题描述】:
我检查了许多网站,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);
}
}
但如果我们在同步块之后使用同步块,则不会出现死锁。
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);
}
}
如果这是获得死锁的唯一方法,那么我们为什么不使用两个单独的同步块呢? 如果还有其他方法可以导致死锁,请举例说明。
【问题讨论】:
-
"为什么我们不使用两个单独的死锁"?你想如何使用死锁??
-
“为什么我们不使用两个单独的死锁”你的意思是为什么不使用两个同步块,一个接一个?是的,这是避免死锁的一种方法。
-
Oracle's Tutorial 上的示例
-
... 在您的示例中,如果您对锁进行顺序化,您将避免死锁,但您将失去线程安全性。正确的解决方案是每个人都以相同的顺序获取锁。
-
Re,“为什么我们不使用两个单独的同步块?”因为那会破坏目的。
synchronized的主要目的是防止任何线程在其他线程正在更改数据时看到处于不一致状态的数据。transfer()示例应该显示其他线程如何在事务之前或事务之后查看数据库,但绝不会在事务中间。但是两个synchronized块之间的差距,无论多么小,都让其他线程有机会在事务仅完成一半时看到它的数据。
标签: java multithreading deadlock