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");
}
}
}
}
運(yùn)行結(jié)果:
Thread1 鎖定user
Thread2 鎖定user2
此時(shí),程序一直執(zhí)行不停止,死鎖現(xiàn)象發(fā)生