Deadlock of thread in java

Deadlock of thread

Deadlock is a part of multithreading. When a thread has locked an object and waiting for another object to be released by another thread and the other thread is also waiting for the first thread to release the first object, both threads are waiting for each other to release the lock. This condition is called thread deadlock.

Example
class bookticket extends Thread
{
Object train, comp;
bookticket(Object train, Object comp)
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(train)
{
System.out.println(“bookticket locked on train”);
try{
Thread.sleep(150);
}catch(InterruptedException e)
{
}
System.out.println(“Bookticket now waiting to lock on compartment”);
synchronized(comp)
{
System.out.println(“Bookticket lock compartment”);
}
}
}
class cancelticket extends Thread
{
Object train, comp;
cancelticket(Object train, Object comp)
{
this.train = train;
this.comp = comp;
}
public void run()
{
synchronized(comp)
{
System.out.println(“cancelticket locked on compartment”);
try{
Thread.sleep(200);
}catch(InterruptedException e)
{
}
System.out.println(“Cancelticket now waiting to lock on train”);
synchronized(train)
{
System.out.println(“Cancelticket lock train”);
}
}
}
}
}
class test
{
public static void main(String[] args)
{
Object train=new Object();
Object compartment=new Object();
bookticket obj1=new bookticket(train, compartment);
cancelticket obj2=new cancelticket(train, compartment);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
}
}

Output:
bookticket locked on train
cancelticket locked on compartment
Bookticket now waiting to lock on compartment
Cancelticket now waiting to lock on train


.
.

Avoiding deadlocks in program
This is no specific solution for the problem of deadlock. It depends on the logic used by the programmer.
For example, in the preceding program, if the programmer used the threads in such a way that the cancelticket thread follows the bookticket, then he could have avoided the deadlock situation.
For this, we change the code in the cancelticket class, cancelticket should be changed as should here:

Example
public void run()
{
synchronized(train)
{
System.out.println(“cancelticket lock on train”);
try{
Thread.sleep(200);
}catch(InterruptedException e)
{
}
System.out.println(“cancelticket now waiting to lock on compartment”);
synchronized(comp)
{
System.out.println(“cancelticket lock compartment”);
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *