Java multithreaded deadlock case (code case)

Java multithreaded deadlock case (code case)

What is deadlock

  • When a thread holds the A object lock and waits for the B object lock, another thread holds the B object lock and waits for the A object lock, which causes a deadlock.
  • A thread can hold the lock marks of multiple objects at the same time. When the thread is blocked, the lock marks it already owns will not be released, and deadlock may also be caused.

Case introduction:

If there is only one pair of shoes left in the dormitory, both Xiao Ming and Xiao Peng will go out at this time. One of them gets the left shoe and the other gets the right shoe, but no one is allowed to give it to anyone, so it almost causes death. No one should go out because of the lock phenomenon.

package com.nxw.Thread.dieLock;

public class DieLock{
    
    

    public static void main(String[] args) {
    
    
        Runnable xiaoming = new Runnable() {
    
    
            public void run() {
    
    
                synchronized (Shoes.left){
    
    
                    System.out.println("小明拿到了左脚鞋子");
                    synchronized (Shoes.right){
    
    
                        System.out.println("小明拿到了右脚鞋子,他可以穿鞋子走人了。。。");
                    }
                }
            }
        };

        Runnable xiaopeng = new Runnable() {
    
    
            public void run() {
    
    
                synchronized (Shoes.right){
    
    
                    System.out.println("小朋拿到了右脚鞋子");
                    synchronized (Shoes.left){
    
    
                        System.out.println("小朋拿到了左脚鞋子,他可以穿鞋子走人了。。。");
                    }
                }
            }
        };

        Thread thread1 = new Thread(xiaoming,"小明");
        Thread thread2 = new Thread(xiaopeng,"小朋");

        thread1.start();
        thread2.start();
    }


}

class Shoes {
    
    
    public static String left = "leftShoes";
    public static String right = "rightShoes";
}

In order to facilitate the posting of code, they are all written into one class.
Run it a few more times and you will find that when Xiao Ming and Xiao Peng happened to grab a shoe, a deadlock occurred.
Insert picture description here

Therefore, we must pay attention to avoid deadlocks when operating multithreading in the work!

Guess you like

Origin blog.csdn.net/nxw_tsp/article/details/109265461