009 Deadlock

I. Overview

  Deadlock is a state:

    Multiple threads compete for multiple locks. If the control is improper, each thread acquires a part of the lock but cannot acquire all the locks, and a deadlock will occur at this time.

  In a normal state, deadlock will always fall into waiting without outside intervention, that is, the program cannot run at all.


 

2. Deadlock

  The state of deadlock is something we don't want to see, but when we encounter it, we need to diagnose and understand where the deadlock occurs.

example: 

public class DaedLock {

    private static Object lock1 = new Object();

    private static Object lock2 = new Object();

    public static void requireLock1() {
        synchronized (lock1) {
            System.out.println(Thread.currentThread().getName()+"获得了lock1");
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName()+"获得了lock2");System.out.println(Thread.currentThread().getName()+ 
                " Obtain all locks and can run " );
                System.out.println("-----------------------");
            }
        }
    }

    public static void requireLock2() {
        synchronized (lock2) {
            System.out.println(Thread.currentThread().getName()+"获得了lock2");
            synchronized (lock1) {
                System.out.println(Thread.currentThread().getName()+"获得了lock1");System.out.println(Thread.currentThread().getName()+ 
                " Obtain all locks and can run " );
                System.out.println("-----------------------");
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                for(;;)
                requireLock1();
            }

        }).start();
        new Thread(new Runnable() {
            public void run() {
                for(;;)
                requireLock2();
            }

        }).start();
    }
}

We create two locks. There are two methods that require both locks to run, but the order in which the locks are acquired is inconsistent.

When running the above code, we will find that there will be no printout for a while, which is the state where the program falls into a deadlock.

The result is as follows:

  

At this point, the two threads have acquired a lock, respectively, but cannot acquire the other's lock. At this time, the two threads wait for each other, and a deadlock occurs.


 3. Understand deadlock through tools

  

First look at all processes

Then use the jstack process ID

  

We have seen a deadlock information, which makes it convenient for us to query the source of the deadlock.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325028092&siteId=291194637
009