How Java Program to Create DeadLock Between Two Threads


In this example we will show how to create deadlock between two threads in Java.

Source Code

package com.beginner.examples;

public class DeadlockExample {
    public static void main(String a[]){
    	final String str1 = "Java";
        final String str2 = "example";
        //  Thread 1
        Thread t1 = new Thread("Thread 1"){
            public void run(){
                while(true){
                    synchronized(str1){
                        synchronized(str2){
                            System.out.println(str1 + " " + str2);
                        }
                    }
                }
            }
        };
        //  Thread 2
        Thread t2 = new Thread("Thread 2"){
            public void run(){
                while(true){
                    synchronized(str2){
                        synchronized(str1){
                            System.out.println(str2 + " " + str1);
                        }
                    }
                }
            }
        };
        t1.start();
        t2.start();
    }
}

Output:

Processing
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments