public class DealThread implements Runnable {
public String userName;
public Object lock1=new Object();
public Object lock2=new Object();
public void setFlag(String userName){
this.userName=userName;
}
@Override
public void run() {
if(userName.equals("a")){
synchronized (lock1){
System.out.println("userName= "+userName);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock2){
System.out.println("按lock1->lock2代码顺序执行了");
}
}
}
if(userName.equals("b")){
synchronized (lock2){
System.out.println("userName= "+userName);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock1){
System.out.println("按lock2->lock1顺序执行了");
}
}
}
}
}
public class Run {
public static void main(String[] args) {
try {
DealThread t1 = new DealThread();
t1.setFlag("a");
new Thread(t1).start();
Thread.sleep(100);
t1.setFlag("b");
new Thread(t1).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
控制台输出:
userName= a
userName= b
cmd 执行 jps 显示java进程的pid
输入jstack 10276或 jstack -l 10276命令,查看死锁原因
死锁位置在DealThread 类 28行
tasklist 显示全部进程、
根据进程名杀死进程
输入:taskkill /f /t /im qq.exe
Taskkill /pid [进程码] -t(结束该进程) -f(强制结束该进程以及所有子进程)
taskkill /pid 10276 -t -f
sa