DeadLock Between Two Threads Example Java Program


Definition

a deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does. a deadlock happens when two processes each within its own transaction updates two rows of information but in the opposite order.

DeadLock Between Two Threads Example Program

public class DeadLockBetweenTwoThreads {
    String strone = "HAI";
    String strtwo = "HELLO";
    Thread t1 = new Thread("Thread One"){
        public void run(){
			while(true){
                synchronized(strone){
                    synchronized(strtwo){
                        System.out.println(strone + strtwo);
                    }
                }
            }
        }
    };
    Thread t2 = new Thread("Thread Two"){
        public void run(){
            while(true){
                synchronized(strtwo){
                    synchronized(strone){
                        System.out.println(strtwo + strone);
                    }
                }
            }
        }
    };
     
    public static void main(String a[]){
        DeadLockBetweenTwoThreads obj = new DeadLockBetweenTwoThreads();
        obj.t1.start();
        obj.t2.start();
    }
}

Sample Output

Output is:
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI