Java hand-write a deadlock and use tools to find the deadlock position [jps, jstack]

package lock;

import java.util.concurrent.ThreadFactory;

/**
* @author Mr.Zhao 
* @Description:  资源竞争类
* @date 2019/12/28 10:16
* @version 1.0 
*/
class LockResource implements Runnable{
    
    
    private String lockA;
    private String lockB;

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

    @Override
    public void run() {
    
    
        synchronized (lockA) {
    
    
            System.out.println(Thread.currentThread().getName() + "自己持有" + lockA + "尝试获取" + lockB);
            synchronized (lockB) {
    
    
                System.out.println(Thread.currentThread().getName() + "自己持有" + lockB + "尝试获取" + lockA);
            }
        }
    }
}

/**
 * @author Mr.Zhao
 * @version 1.0
 * @Description: 手写一个死锁
 * @date 2019/12/28 10:08
 */
public class DeadLock {
    
    
    public static void main(String[] args) {
    
    
        new Thread(new LockResource("lockA","lockB"), "ThreadAAAA").start();
        new Thread(new LockResource("lockB","lockA"), "ThreadBBBB").start();

    }
}

Insert picture description here
Enter jps to view the java process, find the pid of your own process,
Insert picture description here
enter the jstack process id, and view the detailed information.
Insert picture description here
Insert picture description here
You can see that the two threads are waiting for each other and enter a deadlock

May your heart be like flowers and trees

Guess you like

Origin blog.csdn.net/nbcsdn/article/details/103742059