Tuesday, 30 June 2015

Thread Dead lock solution ?

package com.JavaInterview.Programs;

/** * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */
public class DeadlockSolution {

 public static Object lock1 = new Object();
 public static Object lock2 = new Object();

 public static void main(String args[]) {
  Thread1 t1 = new Thread1();
  Thread2 t2 = new Thread2();

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

 private static class Thread1 extends Thread {

  public void run() {
   synchronized (lock1) {
    System.out.println("Thread 1 :holding the lock1 ...");
    try {
     Thread.sleep(10);
    } catch (InterruptedException e) {
    }
    System.out.println("Thread 1 :waiting for lock 2....");
    synchronized (lock2) {
     System.out.println("Thread 1: holding lock1 and 2...");
    }
   }
  }

 }

 private static class Thread2 extends Thread {
  public void run() {
   synchronized (lock1) // to create deadlock use lock2 here
   /*
    * By interchanging locks position we have avoided deadlock
    * here(From creating deadlock example)
    */
   {
    System.out.println("Thread 2 :holding the lock2");
    try {
     Thread.sleep(20);
    } catch (InterruptedException e) {
    }
    System.out.println("Thread 2 : waiting for lock2 ...");
    synchronized (lock2)// to create deadlock use lock1 here
    {
     System.out.println("Thread 2 : holding both lock1 and 2..");
    }
   }
  }
 }
}


Output:
Thread 1 :holding the lock1 ...
Thread 1 :waiting for lock 2....
Thread 1: holding lock1 and 2...
Thread 2 :holding the lock2
Thread 2 : waiting for lock2 ...
Thread 2 : holding both lock1 and 2..


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...