
public class anotherdeadlock {
public static void main(string[] args) {
final object resource1 = "resource1";
final object resource2 = "resource2";
// t1 tries to lock resource1 then resource2
thread t1 = new thread() {
public void run() {
// lock resource 1
synchronized (resource1) {
system.out.println("thread 1: locked resource 1");
try {
thread.sleep(50);
} catch (interruptedexception e) {
}
synchronized (resource2) {
system.out.println("thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
thread t2 = new thread() {
public void run() {
synchronized (resource2) {
system.out.println("thread 2: locked resource 2");
try {
thread.sleep(50);
} catch (interruptedexception e) {
}
synchronized (resource1) {
system.out.println("thread 2: locked resource 1");
}
}
}
};
// if all goes as planned, deadlock will occur,
// and the program will never exit.
t1.start();
t2.start();
}
}
闽公网安备 35060202000074号