Untitled
Anonymous
Plain Text
10/14/2025 4:14 PM
2.2 KB
18
Indexable
Never
//Java Program to avoid deadlock
public class Main {
public static void main(String ar[]) {
Main test = new Main();
final resource1 a = test.new resource1();
final resource2 b = test.new resource2();
// Thread - 1
Runnable t1 = new Runnable() {
public void run() {
synchronized (b) {
try {
/* Adding delay so that both threads can start trying to lock resources */
Thread.sleep(100);
System.out.println("In block 1111");
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread - 1 have resource2 but need resource1 also
synchronized (a) {
System.out.println("In block 1");
}
}
}
};
// Thread - 2
Runnable t2 = new Runnable() {
public void run() {
synchronized (b) {
try {
/* Adding delay so that both threads can start trying to lock resources */
Thread.sleep(100);
System.out.println("In block 22222");
} catch (InterruptedException e) {
e.printStackTrace();
}
// System.out.println("In block 222222");
// Thread - 2 have resource2 but need resource1 also
synchronized (a) {
System.out.println("In block 2");
}
}
}
};
new Thread(t1).start(); // first thread
new Thread(t2).start(); // second thread
}
// resource1
private class resource1 {
private int i = 10;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
// resource2
private class resource2 {
private int i = 20;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
} Editor is loading...
Leave a Comment