1, concept,

Deadlock refers to two or more of the above process in the process of execution, due to competition for resources, a kind of wait for each other, without external force to interfere in that they will not be able to push down, if the resource is enough, the process of resource requests can be satisfied, the possibility of deadlocks occur is very low, otherwise it will be because of competing for the limited resources into a deadlock.

Cause of deadlock

System resources are insufficient. Processes run in incorrect order and resources are improperly allocated

Four necessary conditions for a deadlock to occur

Mutually exclusive solution: Encapsulate mutually exclusive shared resources as simultaneously accessible possessive-and-wait solution: when a process requests a resource, it is required that it does not occupy any other resources, that is, it must apply for all resources at once. This approach leads to resource inefficiency. Non-preemptive solution: if the process cannot allocate resources immediately, it is required that it does not occupy any other resources, that is, only when it can obtain all of the required resources at the same time. Solution: Sort the resources, requiring the process to request resources in order.

Deadlock code

public class DeadLock {
    public static void main(String[] args) {
        Resource666 res1 = new Resource666();
        Resource666 res2 = new Resource666();
        res1.flag = true;
        res2.flag = false;
        new Thread(new Runnable() {
            @Override
            public void run() { res1.method(); }},"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() { res2.method(); }},"B").start();
    }
}

class Resource666 {
    boolean flag = true;
    private static final Object obj1 = new Object();
    private static final Object obj2 = new Object();

    public void method() {
        if (flag) {
            synchronized (obj1) {
                System.out.println(Thread.currentThread().getName() + "" + "Lock 1 obtained");
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj2) {
                    System.out.println(Thread.currentThread().getName() + "" + "Lock 2 obtained"); }}}else {
            synchronized (obj2) {
                System.out.println(Thread.currentThread().getName() + "" + "Lock 2 obtained");
                synchronized (obj1) {
                    System.out.println(Thread.currentThread().getName() + "" + "Lock 1 obtained");
                }
            }
        }
    }
}

Copy the code

3. How to check deadlocks

When we have a deadlock, we first need to use the JPS command to see what is running

View stack information using jStack

jstack  5116  The following argument is the PID of the class output by JPS
Copy the code

The results obtained