I have checked many websites and the only example of deadlock
is something like this. There is always a synchronized
block inside a synchronized
block.
(method withdraw
is locked by a
and method deposit
is locked by 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);
}
}
but if we use a synchronized block after a synchronized block there will be no deadlock.
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);
}
}
If this is the only way to get deadlock then why don't we use two separate synchronized block? If there are other ways to get deadlock please give example.