/*** @author:cp* @time:2021-2-24* @Description: java死锁测试* 进程id查看命令:jsp 找到对应的进程id* 通过jstack 进程id 输出死锁信息** 如何定位死循环导致的其他线程阻塞等待:* linux下top命令查看cpu使用率较高的java进程,进而用top -Hp ➕pid查看该java进程下cpu使用率较高的线程。再用jstack命令查看线程具体调用情况,排查问题。*/
public class DeadLockSample extends Thread {private String first;private String second;public DeadLockSample(String name, String first, String second) {super(name);this.first = first;this.second = second;}public void run() {synchronized (first) {System.out.println(this.getName() + " obtained: " + first);try {Thread.sleep(1000L);synchronized (second) {System.out.println(this.getName() + " obtained: " + second);}} catch (InterruptedException e) {// Do nothing}}}//死锁/*public static void main(String[] args) throws InterruptedException {String lockA = "lockA";String lockB = "lockB";DeadLockSample t1 = new DeadLockSample("Thread1", lockA, lockB);DeadLockSample t2 = new DeadLockSample("Thread2", lockB, lockA);t1.start();t2.start();t1.join();t2.join();}*/public static void main(String[] args) throws InterruptedException {ThreadMXBean mbean = ManagementFactory.getThreadMXBean();Runnable dlCheck = new Runnable() {@Overridepublic void run() {long[] threadIds = mbean.findDeadlockedThreads();if (threadIds != null) {ThreadInfo[] threadInfos = mbean.getThreadInfo(threadIds);System.out.println("Detected deadlock threads:");for (ThreadInfo threadInfo : threadInfos) {System.out.println(threadInfo.getThreadName());}}}};ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);// 稍等5秒,然后每10秒进行一次死锁扫描scheduler.scheduleAtFixedRate(dlCheck, 5L, 10L, TimeUnit.SECONDS);//死锁代码String lockA = "lockA";String lockB = "lockB";DeadLockSample t1 = new DeadLockSample("Thread1", lockA, lockB);DeadLockSample t2 = new DeadLockSample("Thread2", lockB, lockA);t1.start();t2.start();t1.join();t2.join();}
}
上述代码示例会产生死锁
总结:
1、进程id查看命令:jsp 找到对应的进程id * 通过jstack 进程id 输出死锁信息 2、如何定位死循环导致的其他线程阻塞等待: * linux下top命令查看cpu使用率较高的java进程,进而用top -Hp ➕pid查看该java进程下cpu使用率较高的线程。再用jstack命令查看线程具体调用情况,排查问题。