欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

死锁编码及定位分析

程序员文章站 2022-04-17 22:35:30
...

死锁编码及定位分析

是什么

​ 死锁是指两个或两个以上的进程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力干涉,他们都将无法进行下去,如果系统资源充足,进行的资源请求都能够得到满足,死锁出现的可能性就很低,否则就回因争夺有限的资源而陷入死锁.

package top.ygy.thread;

public class DeadLockDemo {
	public static void main(String[] args) {
		String lockA = "lockA";
		String lockB = "lockB";
		
		new Thread(new HoldLockTHread(lockA,lockB),"ThreadAAA").start();
		new Thread(new HoldLockTHread(lockB,lockA),"ThreadBBB").start();
	}
}

class HoldLockTHread implements Runnable {

	private String lockA;
	private String lockB;

	public HoldLockTHread(String lockA, String lockB) {
		this.lockA = lockA;
		this.lockB = lockB;
	}

	@Override
	public void run() {
		synchronized (lockA) {
			System.out.println(Thread.currentThread().getName() + "\t 自己持有:"
					+ lockA + ",尝试获得:" + lockB);
			synchronized (lockB) {
				System.out.println(Thread.currentThread().getName() + "\t 自己持有:"
						+ lockB + ",尝试获得:" + lockA);
			}
		}
	}

}

产生原因

  1. 系统资源不足
  2. 进程运行推进的顺序不合适
  3. 资源分配不当

解决

工具

  • jps 命令类似与 linux 的 ps 命令,但是它只列出系统中所有的 Java 应用程序。
  • jstack是java虚拟机自带的一种堆栈跟踪工具

查看进程?

  • linux ps -ef | grep xxxx ls -f
  • windows下的java运行程序,也有类似查看进程的命令,但是我们目前查看的只是java
    • jsp -l
  • jsp查出端口号,用jstack查看具体信息
    • jstack 端口号
C:\Users\Administrator>jps -l
55408 sun.tools.jps.Jps
56256 top.ygy.thread.DeadLockDemo
46376
C:\Users\Administrator>jstack 56256

Found one Java-level deadlock:
=============================
"ThreadBBB":
  waiting to lock monitor 0x0000000057086768 (object 0x00000000d60ca108, a java.
lang.String),
  which is held by "ThreadAAA"
"ThreadAAA":
  waiting to lock monitor 0x0000000057089208 (object 0x00000000d60ca140, a java.
lang.String),
  which is held by "ThreadBBB"

Java stack information for the threads listed above:
===================================================
"ThreadBBB":
        at top.ygy.thread.HoldLockTHread.run(DeadLockDemo.java:29)
        - waiting to lock <0x00000000d60ca108> (a java.lang.String)
        - locked <0x00000000d60ca140> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"ThreadAAA":
        at top.ygy.thread.HoldLockTHread.run(DeadLockDemo.java:29)
        - waiting to lock <0x00000000d60ca140> (a java.lang.String)
        - locked <0x00000000d60ca108> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.