java手写一个死锁并用工具查找死锁位置【jps,jstack】
程序员文章站
2024-03-24 21:26:16
...
package lock;
import java.util.concurrent.ThreadFactory;
/**
* @author Mr.Zhao
* @Description: 资源竞争类
* @date 2019/12/28 10:16
* @version 1.0
*/
class LockResource implements Runnable{
private String lockA;
private String lockB;
public LockResource(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName() + "自己持有" + lockA + "尝试获取" + lockB);
synchronized (lockB) {
System.out.println(Thread.currentThread().getName() + "自己持有" + lockB + "尝试获取" + lockA);
}
}
}
}
/**
* @author Mr.Zhao
* @version 1.0
* @Description: 手写一个死锁
* @date 2019/12/28 10:08
*/
public class DeadLock {
public static void main(String[] args) {
new Thread(new LockResource("lockA","lockB"), "ThreadAAAA").start();
new Thread(new LockResource("lockB","lockA"), "ThreadBBBB").start();
}
}
输入jps查看java进程,查找自己进程的pid
输入jstack 进程id,查看详细信息
可以看到两个线程相互等待,进入死锁