The deadlock phenomenon of multithreading in Java and demonstrate a deadlock case


Preface

Deadlock is an important content in Java multithreading, so the understanding of deadlock is very important. During the interview, programmers are often asked to write a deadlock case.

1. What is a deadlock

  • Let's give an example in life. Chinese people eat with foreigners. Chinese people use chopsticks and foreigners use forks to finish the meal smoothly.
  • So what is a deadlock phenomenon? If the foreigner is holding the chopsticks and the Chinese is holding the fork, and neither of them will give it to anyone, then there will be a stalemate and no one can eat.
  • After the deadlock phenomenon occurs, there will be no exceptions and no prompts, but all threads will be blocked and cannot continue.

Two, deadlock case

  1. Create a LockUtils interface
public interface LockUtils {
    
    
    Object Obj1 = new Object();
    Object Obj2 = new Object();
}

  1. Main program
public class 死锁现象 implements LockUtils {
    
    
    public static void main(String[] args) {
    
    
        MyThread10 th1 = new MyThread10(true);
        MyThread10 th2 = new MyThread10(false);
        th1.start();
        th2.start();

    }

}
class  MyThread10 extends Thread {
    
    
    private boolean flag;

    public MyThread10(boolean flag) {
    
    
        this.flag = flag;
    }

    @Override
    public void run() {
    
    
        if (flag) {
    
    
        //同步代码块嵌套
            synchronized (LockUtils.Obj1) {
    
    
                System.out.println("true线程持有obj1锁,进来了");
                synchronized (LockUtils.Obj2) {
    
    
                    System.out.println("true线程持有obj2锁,进来了");
                }
            }

        } else {
    
    
            synchronized (LockUtils.Obj2) {
    
    
                System.out.println("false线程持有obj2锁,进来了");
                synchronized (LockUtils.Obj1) {
    
    
                    System.out.println("false线程持有obj1锁,进来了");
                }

            }

        }
    }
}

Running result: The
Insert picture description here
true thread takes the obj1 lock and outputs the statement. The false thread takes the obj2 lock and outputs the statement. Both threads are waiting for the resource to be released, and the resource is locked by another thread, causing each thread to wait for the target thread to release its lock, resulting in deadlock.

Guess you like

Origin blog.csdn.net/m0_46988935/article/details/112896652