Thursday, January 16, 2014

DeadLock

Deadlock can occur in a situation when a Thread is waiting for die. An object lock that is used by another Thread and second Thread is waiting for an object that is used by first Thread. Since both Threads are waiting for each other to release the lock, this condition is called deadlock.


public class deadExp4
{
public static void main(String surat[])
{
final String m1="Mahi";
final String m2="Rupal";

Thread t1=new Thread()
{
public void run()
{
synchronized(m1)
{
System.out.println("Thread1 : locked m1");
try
{
Thread.sleep(500);
}
catch(Exception e){}

synchronized(m2)
{
System.out.println("Thread1 : locked m2");
}
}
}
};
Thread t2=new Thread()
{
public void run()
{
synchronized(m2)
{
System.out.println("Thread2 : locked m2");
try
{
Thread.sleep(500);
}
catch(Exception e){}

synchronized(m1)
{
System.out.println("Thread2 : Locked m1");
}
}
}
};
t1.start();
t2.start();
}
}

Output:

No comments:

Post a Comment