In below program thread t1 and t2 are waiting for each other to release the lock. So, there will be a deadlock and "Thread 1: locked resource 2" and "Thread 2: locked resource 1" statements will never print.
package testjava.multithreading;
public class CreateDeadlock
{
public static void main(String[] args)
{
final String resource1 = "My First Resource";
final String resource2 = "My Second Resource";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread()
{
public void run()
{
synchronized(resource1)
{
System.out.println("Thread 1: locked resource 1");
try
{
Thread.sleep(1);
}
catch(Exception e)
{
}
synchronized(resource2)
{
System.out.println("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread()
{
public void run()
{
synchronized(resource2)
{
System.out.println("Thread 2: locked resource 2");
try
{
Thread.sleep(1);
}
catch (Exception e)
{
}
synchronized(resource1)
{
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2