A持有B锁,B持有A锁,都需要对方的锁,最直接的死锁案例
只要不是死锁就和谐了吧,,这个怎么写
class LockA
{
public static final LockA locka = new LockA();
}
class LockB
{
public static final LockB lockb = new LockB();
}
class Dead implements Runnable
{
boolean flag = true;
Dead (boolean flag){
this.flag = flag;
}
public void run(){
while(true){
if(flag==true){
synchronized(LockA.locka){
System.out.println("if------持有A锁");
synchronized(LockB.lockb){
System.out.println("if-------持有B锁");
}
}
}
else{
synchronized(LockB.lockb){
System.out.println("else------持有B锁");
synchronized(LockA.locka){
System.out.println("else------持有A锁");
}
}
}
}
}
}
class DeadLock
{
public static void main(String[] args)
{
Dead d1 = new Dead(true);
Dead d2 = new Dead(false);
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}
}
|