我试图在这个程序中实现死锁条件 这个程序没有给出死锁条件。为什么? 请告诉我这段代码有什么问题。
输出是:
Thread1 : locked Integer
Thread2 : locked String
Thread1 : locked String
Thread2 : locked Integer
代码:
class Dead {
public void meth1() {
synchronized (Integer.class) {
System.out.println("Thread 1: locked Integer");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (String.class) {
System.out.println("Thread 1: locked String");
}
}
public void meth2() {
synchronized (String.class) {
System.out.println("Thread 2: locked String");
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e);
}
synchronized (Integer.class) {
System.out.println("Thread 2: locked Integer");
}
}
}
class MThread1 extends Thread {
Dead d;
MThread1(Dead d) {
this.d = d;
}
public void run() {
d.meth1();
}
}
class MThread2 extends Thread {
Dead d;
MThread2(Dead d) {
this.d = d;
}
public void run() {
d.meth2();
}
}
public class Thread1 {
public static void main(String[] args) {
// Dead d = new Dead();
MThread1 t1 = new MThread1(new Dead());
MThread2 t2 = new MThread2(new Dead());
t1.start();
t2.start();
}
}
最佳答案
当你写的时候
synchronized (Integer.class) {
System.out.println("Thread 1: locked Integer");
}
它锁定 Integer.class 对象并立即解锁它。你想要这个:
synchronized(Integer.class) {
System.out.println("Thread 1: locked Integer");
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
System.out.println(e);
}
synchronized(String.class) {
System.out.println("Thread 1: locked String");
}
}
关于java - 程序不会导致死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421967/