1 2 3 package deadlock; 4 5 public DeadlockTest extends Thread { 6 7 public static Object lock1 = new Object(); 8 public static Object lock2 = new Object(); 9 public void method1() { 10 synchronized (lock1) { 11 delay(500); //some operation 12 System.out.println("method1: " + Thread.currentThread().getName()); 13 synchronized (lock2) { System.out.println("method1 is executing .... "); 14 } 15 } 16 } 17 18 public void method2() { 19 synchronized { delay(500); //some operation 20 System.out.println("method1: " + Thread.currentThread().getName()); 21 synchronized (lock1) { 22 System.out.println("method2 is executing .... "); 23 } 24 } } 25 26 @Override 27 public void run() { 28 method1(); 29 method2(); } 30 31 public static void main(String[] args) { 32 DeadlockTest thread1 = new DeadlockTest(); 33 DeadlockTest thread2 = new DeadlockTest(); 34 35 36 } 37 38 /** 39 * The delay is to simulate some real operation happening. 40 * @param timeInMillis 41 */ private void delay(long timeInMillis) { 42 try { 43 44 } (InterruptedException e) { 45 e.printStackTrace(); 46 } } 47 48 } 49 50 51
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package deadlock; public DeadlockTest extends Thread { public static Object lock1 = new Object(); public static Object lock2 = new Object(); public void method1() { synchronized (lock1) { delay(500); //some operation System.out.println("method1: " + Thread.currentThread().getName()); synchronized (lock2) { System.out.println("method1 is executing .... "); } } } public void method2() { synchronized { delay(500); //some operation System.out.println("method1: " + Thread.currentThread().getName()); synchronized (lock1) { System.out.println("method2 is executing .... "); } } } @Override public void run() { method1(); method2(); } public static void main(String[] args) { DeadlockTest thread1 = new DeadlockTest(); DeadlockTest thread2 = new DeadlockTest(); } /** * The delay is to simulate some real operation happening. * @param timeInMillis */ private void delay(long timeInMillis) { try { } (InterruptedException e) { e.printStackTrace(); } } }
Java%20Multi-Threading%20Questions%20Answers.docx