Wednesday, June 15, 2016

Thread(Deadlock of Threads) example java

Deadlock of Threads:

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 the threads will continue waiting forever.This is called "Thread Deadlock" .

Even if we synchronize the threads ,there is possibility of other problems like deadlock.

Program:

/**
 * @author Abhinaw.Tripathi
 *
 */
class BookTicket extends Thread
{
  Object train,compartment;

  public BookTicket(Object train,Object comp)
  {
this.train=train;
this.compartment=comp;
  }

  public void run()
  {
 synchronized (train)
 {
System.out.println("BookTicket locked on train");
try
{
Thread.sleep(150);
}
catch (InterruptedException e)
{
e.printStackTrace();
}

synchronized (compartment)
{
System.out.println("Book Ticket locked on compatrment");
}

 }
  }

}

class CancelTicket extends Thread
{
   Object train,compartnment;
 
   public CancelTicket(Object train,Object comp)
   {
this.compartnment=comp;
this.train=train;
   }
 
   public void run()
   {
  synchronized (compartnment)
  {
System.out.println("Canceal Ticket locked on compartment");
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Canceal Ticket  now waiting to lock on train.....");
synchronized (train)
{
System.out.println("Cancel Ticket locked on train");
}
  }
   }
 
}

public class DeadLockApp
{
public static void main(String[] args)
{
Object train=new Object();
Object comp=new Object();

BookTicket obj1=new BookTicket(train, comp);
CancelTicket obj2=new CancelTicket(train, comp);

Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);

t1.start();
t2.start();

}


}

Output:

BookTicket locked on train
Canceal Ticket locked on compartment
Canceal Ticket  now waiting to lock on train.....

Avoiding Deadlocks in a Program:

There is specific solution for the problem of deadlocks.It depends on the logic used by the programmer.The programmer should design his program in such a way that it does not form any deadlock.

No comments: