TestDeadLock.java:
package com.ctgu.testDeadLock;
public class TestDeadLock {
public static void main(String[] args) {
User user = new User("大毛", "123", 22);
User user2 = new User("二毛", "456", 44);
new Thread1("Thread1", user, user2).start();
new Thread2("Thread2", user, user2).start();
}
}
Thread1.java:
package com.ctgu.testDeadLock;
public class Thread1 extends Thread{
private User user;
private User user2;
public Thread1(String name, User user, User user2) {
this.setName(name);
this.user = user;
this.user2 = user2;
}
@Override
public void run() {
synchronized (user) {
System.out.println(Thread.currentThread().getName() + " 锁定user");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (user2) {
System.out.println(Thread.currentThread().getName() + " 锁定user2");
}
}
}
}
Thread2.java:
package com.ctgu.testDeadLock;
public class Thread2 extends Thread{
private User user;
private User user2;
public Thread2(String name, User user, User user2) {
this.setName(name);
this.user = user;
this.user2 = user2;
}
@Override
public void run() {
synchronized (user2) {
System.out.println(Thread.currentThread().getName() + " 锁定user2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (user) {
System.out.println(Thread.currentThread().getName() + " 锁定user");
}
}
}
}
运行结果:
Thread1 锁定user
Thread2 锁定user2
此时,程序一直执行不停止,死锁现象发生