java deadlock demo

java deadlock demo

Deadlock generated simulation

Deadlocks are caused by multiple threads competing for the same resources


package com.feshfans;

/**
 * 1. 本代码为展示 java 中死锁的产生
 * 2. 死锁的排查方法
 */
public class DeadlockShow {

    // 声明两个资源
    private static final String ResourceA = "A";
    private static final String ResourceB = "B";

    private static void deadlock(){

        Thread t1= new Thread(new Runnable() {
            @Override
            public void run() {
                // 线程 A 先获取 ResourceA,即线程A持有 ResourceA 的锁
                synchronized (ResourceA){
                    System.out.println("T1 get resource A");
                    try {
                        // 休眠 2 秒,目的是为了让线程 B 有足够的时间获取 ResourceB
                        // 为什么要用 sleep,因为 sleep 方法不会释放锁对象
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (ResourceB){
                        System.out.println("T1 get resource B");
                    }

                }

            }
        },"Thread-A");

        Thread t2= new Thread(new Runnable() {
            @Override
            public void run() {
                // 线程 B 先获取 ResourceB,即线程 B 持有 ResourceB 的锁
                synchronized (ResourceB){
                    System.out.println("T2 get resource B");
                    try {
                        // 休眠 1 秒,目的是为了让线程 A 有足够的时间获取 ResourceA
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (ResourceA){
                        System.out.println("T1 get resource A");
                    }
                }

            }
        }, "Thread-B");

        // 启动两个线程
        t1.start();
        t2.start();
    }

    public static void main(String[] args) {
        deadlock();
        // 主线程并不会退出,因为 deadlock() 产生的死锁,子线程一直没有执行完
    }
}
Deadlock View
  1. First view java process using jps pid, as shown:

View java process
View java process

  1. Use jstack view java stack information, as shown:

    View deadlock information

From the above figure we can clearly see the number of deadlock, which creates a deadlock between several threads, memory address resources and resource types of competition between threads (String in this example), line of code deadlock number and other information

Personal recommendations, it in the open thread for each thread is given a name, so that when problems arise, would be particularly clear

Guess you like

Origin www.cnblogs.com/feshfans/p/11297947.html