java 多线程:线程死锁,如何判断程序是否有死锁代码块儿
线程死锁
死锁是指两个或两个以上的线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去(百度百科)。
代码示例:
/** * @ClassName ThreadDeadLock * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/22. */ public class ThreadDeadLock { private static class MyDeadLockRunnable implements Runnable{ private Object lockA = new Object(); private Object lockB = new Object(); @Override public void run() { String tName = Thread.currentThread().getName(); try { if ("A".equals(tName)){ runA(); }else { runB(); } }catch (InterruptedException e){e.printStackTrace();} } private void runA() throws InterruptedException { synchronized (lockA){ System.out.println("我开始运行了,我是A"); Thread.sleep(1000); synchronized (lockB){ System.out.println("我运行完了,我是A"); } } } private void runB() throws InterruptedException { synchronized (lockB){ System.out.println("我开始运行了,我是B"); Thread.sleep(1000); synchronized (lockA){ System.out.println("我运行完了,我是B"); } } } } public static void main(String[] args) { Runnable myDeadlock = new MyDeadLockRunnable(); new Thread(myDeadlock,"A").start(); new Thread(myDeadlock,"B").start(); } }
运行结果:
打印了两句话:
如何判断我们写的程序是有死锁
1,jps -l 命令来获取对应的进程pid:
2,获取到对应的Pid之后用jstack命令来查看是否有死锁:
jstack -l 26640
posted on 2021-04-22 20:23 zhangmingda 阅读(272) 评论(0) 编辑 收藏 举报