How deadlock occurs in Threads?

In multithreading deadlock situation may occur, when two or more threads compete for two or more resource. Below is simple example, in which threads t1 and t2 compete to lock two objects obj1 and obj2, which end up in deadlock situation.

Thread deadlock
Thread deadlock

After t1 and t2 threads are started, deadlock occurs in following way
1. Thread t1 locks obj1
2. Thread t2 locks obj2
3. Thread t1 tries to lock obj2
4. Thread t2 tries to lock obj1
5. deadlock occurs…and program hangs

class MyThread8 extends Thread{
	Object obj1, obj2;
	
	MyThread8(Object obja, Object objb)
	{
		obj1 = obja;
		obj2 = objb;
	}
	
	public void run(){
        while(true){
            synchronized(obj1){
                synchronized(obj2){
                System.out.println(obj1+"  "+obj2);
                }
            }
        }
    }
}

public class ThreadDeadLockDemo {
     
    public static void main(String a[]){
        String str1 = "first string";
        String str2 = "second string";
        
    	MyThread8 t1 = new MyThread8(str1,str2);
    	
    	MyThread8 t2 = new MyThread8(str2,str1);
    	
    	t1.start();
    	t2.start();
    }
}

How to avoid deadlocks?
It is possible to avoid deadlocks, by taking care of order of locking, while programming. main method in above program can be re written as below, to avoid deadlock.

public class ThreadDeadLockDemo {
     
    public static void main(String a[]){
        String str1 = "first string";
        String str2 = "second string";
        
    	MyThread8 t1 = new MyThread8(str1,str2);
    	
    	MyThread8 t2 = new MyThread8(str1,str2);
    	
    	t1.start();
    	t2.start();
    }
}

Below are steps involved
1.Thread t1 locks str1
2.Thread t2 attempts to lock str1, waits until t1 unlocks str1
3.Thread t1 locks str2
4.Thread t1 unlocks str2
5.Thread t1 unlocks str1
6.Thread t2 acquires lock on str1
….and so on.

Hence deadlock does not occur, in this case.

You may also like to read:
Create Child Thread, from another Child Thread
Advantages of Concurrent Collection over Synchronized Collection
How to create multiple threads