What is a deadlock?
A deadlock occurs when two threads compete with each other for resources they hold.
For example, A holds an apple and B holds A banana. A eats A banana when he wants an apple, while B eats an apple when he wants A banana
Code interpretation
Start by creating a resource class and implementing the Runnable interface.
Two resources are defined as lockA lockB.
Class MyThread implements Runnable{// resources private String implements Runnable; private String lockB; MyThread(String lockA,String lockB){this.lockA = lockA; this.lockB = lockB; } // omit the run method firstCopy the code
Then, as in the previous example, when the thread gets the lockA, we hope it won’t release the lockA and try to compete with the lockB, and the other thread will do the same
So our run method is written as follows:
@override public void run() {// The lockA is not a literal lockA. For example, the lockA is changed when different values are passed to the parameter constructor of Mythread Synchronized (lockA){Mythread(lockB,lockA); synchronized(lockA){ System.out.println(" I am Lock"+ thread.currentThread ().getName()+" I am gun to "+lockA+" Lock now about to get "+lockB+" Lock...." ); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lockB){system.out.println (" never get a lock "); }}}Copy the code
Main method code:
public class deadLockDemo { public static void main(String[] args) { String lockA = "lockA"; String lockB = "lockB"; New Thread(new MyThread(lockA,lockB),"A").start(); New Thread(new MyThread(lockB,lockA),"B").start(); }}Copy the code
Results:
How do I view deadlocks?
Use two commands.
JPS -l (ps is the command to view the process on Linux), you can see the deadLockDemo process number that is currently running.
Then execute the jStack process number to check the process information to find the deadlock problem.
Printed out a bunch of… Now slide down to the bottom
Display the cause of deadlock, convenient for us to locate the investigation.
This is a personal note…