Hi Vali,
Try this code. This creates a deadlock between the two threads.
public class TestThreadSync implements Runnable
{
String A = new String("Siyaa1");
String B = new String("Siyaa2");
public static void main(String[] args)
{
TestThreadSync mainClass = new TestThreadSync();
Thread t1 = new Thread(mainClass);
Thread t2 = new Thread(mainClass);
t1.setName("T1");
t2.setName("T2");
t1.start();
t2.start();
}
public void run()
{
try{
if(Thread.currentThread().getName().equals("T1"))
{
System.out.println("Thread T1 launched");
synchronized(A)
{
System.out.println("Thread T1 got lock on A");
Thread.sleep(10000);
synchronized(B){
System.out.println("T1 managed both");
}
}
}
if(Thread.currentThread().getName().equals("T2"))
{
System.out.println("Thread T2 launched");
synchronized(B)
{
System.out.println("Thread T2 got lock on B");
Thread.sleep(10000);
synchronized(A){
System.out.println("T2 managed both");
}
}
}
}
catch(Exception e)
{
System.out.println("Exception - "+e.getMessage());
}
}
}
The output that I see is -
C:\Test>
java TestThreadSync
Thread T1 launched
Thread T1 got lock on A
Thread T2 launched
Thread T2 got lock on B
And the program just hangs there. This is what I expected it to do when entered in a deadlock situation.