Reset search java concurrent programming-demonstration and troubleshooting of deadlock phenomenon

Demonstration and troubleshooting of deadlock phenomenon

Run the following code in the IDE tool and find that it does not exit. Click the DeadLockDemoclass, right-click, open in Terminaland open the console.

package thread;

import java.util.concurrent.TimeUnit;

public class DeadLockDemo {
    
    
    public static void main(String[] args) {
    
    
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA, lockB), "ThreadA").start();
        new Thread(new HoldLockThread(lockB, lockA), "ThreadB").start();
    }
}

class HoldLockThread implements Runnable {
    
    
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
    
    
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
    
    
        synchronized (lockA) {
    
    
            System.out.println(Thread.currentThread().getName() + "\t自己持有:" + lockA + "\t尝试获取:" + lockB);
            try {
    
    
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
            synchronized (lockB) {
    
    
                System.out.println(Thread.currentThread().getName() + "\t自己持有:" + lockB + "\t尝试获取:" + lockA);
            }
        }
    }
}

Input box jps -l, view thread list, input jstack 线程ID.

jps -l

jps command

jstack 7104

Insert picture description here
At this time, a deadlock was discovered. Found 1 deadlock..

Guess you like

Origin blog.csdn.net/e891377/article/details/108752132