Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write comment on each line Write a Program in Java to create two methods in a cl

ID: 3869524 • Letter: W

Question

write comment on each line


Write a Program in Java to create two methods in a class. In first method make two synchronized block to lock String class and Integer class. In the second method lock the above two classes in the reverse order Inside main method creates a thread and call the above methods. This will create a deadlock . . Remove the deadlock from the code 6. Expected Output The expected output should be displayed on the eclipse console Files to be submitted for verification 1. Edlipse Console Screenshot with the relevant output. 2. Eclipse files in below format

Explanation / Answer

Hi,

Please see the code with deadlock:

Deadlock.java

public class Deadlock {

public static void main(String [] args){

Thread1 deadlockThread1 = new Thread1();

Thread2 deadlockThread2 = new Thread2();

deadlockThread1.start();

deadlockThread2.start();

}

}

class Thread1 extends Thread {

public void run() {

method1();

}

/**

* Method1 acquires lock on String and Integer class

* @param value

*/

public static void method1(){

try{

synchronized(String.class){

System.out.println("Method 1 , String locked");

Thread.sleep(10);

}

synchronized(Integer.class){

System.out.println("Method 1 , Integer locked");

Thread.sleep(10);

}

}catch(Exception e){

}

}

}

class Thread2 extends Thread {

public void run() {

method2();

}

/**

* Method2 acquires lock on String and Integer class in reverse order

* @param value

*/

public static void method2(){

try{

synchronized(Integer.class){

System.out.println("Method 2 , Integer locked");

Thread.sleep(10);

}

synchronized(String.class){

System.out.println("Method 2 , String locked");

Thread.sleep(10);

}

}

catch(Exception e){

}

}

}

Console output: