Program/Code to Create Deadlock Between Two Threads in Java

What is Deadlock ?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
A  deadlock can occur in java  when the synchronized keyword causes the executing thread to block  while waiting for the lock, or monitor associated with the specified object. Since the thread might already holds the object associated with other objects , two threads could be waiting for each other to release a lock, in such case, they will end up waiting forever.

Read Also : Difference between Runnable and Callable in Java

Program/Code to Create Deadlock between Two Threads in Java




public class DeadlockProgram {
 
    String str1 = "Hello";
    String str2 = "USA";
     
    Thread trd1 = new Thread("My Thread 1"){
        public void run(){
            while(true){
                synchronized(str1){
                    synchronized(str2){
                        System.out.println(str1 + str2);
                    }
                }
            }
        }
    };
     
    Thread trd2 = new Thread("My Thread 2"){
        public void run(){
            while(true){
                synchronized(str2){
                    synchronized(str1){
                        System.out.println(str2 + str1);
                    }
                }
            }
        }
    };
     
    public static void main(String a[]){
        MyDeadlock mdl = new MyDeadlock();
        mdl.trd1.start();
        mdl.trd2.start();
    }
}


Please mention in comments if you have any questions regarding deadlock.




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry