Q. What is wrong with the following Java code? Explain what does the following code do? Explain if there is anything wrong with the following code? If there is something wrong, how will you go about fixing it?
|
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 52 53 54 55 56 57 58 |
package what.is.wrong; public class WhatIsWrong1 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 (lock2) { delay(500); //some operation System.out.println("method2: " + Thread.currentThread().getName()); synchronized (lock1) { System.out.println("method2 is executing .... "); } } } @Override public void run() { method1(); method2(); } public static void main(String[] args) { WhatIsWrong1 thread1 = new WhatIsWrong1(); thread1.setName("worker-thread1"); WhatIsWrong1 thread2 = new WhatIsWrong1(); thread2.setName("worker-thread2"); thread1.start(); thread2.start(); } /** * The delay is to simulate some real operation happening. * @param timeInMillis */ private void delay(long timeInMillis) { try { Thread.sleep(timeInMillis); } catch (InterruptedException e) { e.printStackTrace(); } } } |
A….