During the interview the interviewer might ask you knowledge about locks and make you a handwritten deadlock case. Let's write a simple little Demo to achieve a deadlock.
Deadlock Case
1 public class DeadLockDemo extends Thread{ 2 3 String lockA ; 4 String lockB; 5 public DeadLockDemo(String name,String lockA,String lockB){ 6 super(name); 7 this.lockA = lockA; 8 this.lockB = lockB; 9 } 10 11 public void run() { 12 synchronized (lockA){ 13 System.out.println(Thread.currentThread().getName() + "拿到了" + lockA + ",等待拿到" + lockB); 14 try { 15 Thread.sleep(1000); 16 synchronized (lockB){ 17 System.out.println(Thread.currentThread().getName() + "拿到了" + lockB); 18 } 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 23 } 24 } 25 26 public static void main(String[] args){ 27 String lockA = "lockA"; 28 String lockB = "lockB"; 29 DeadLockDemo threadA = new DeadLockDemo("ThreadA", lockA, lockB); 30 DeadLockDemo threadB = new DeadLockDemo("ThreadB", lockB, lockA); 31 threadA.start(); 32 threadB.start(); 33 try { 34 threadA.join(); 35 threadB.join(); 36 } catch (InterruptedException e) { 37 e.printStackTrace(); 38 } 39 } 40 }
This code block will live to see obvious results
ThreadA got lockA, waiting to get lockB
ThreadB got lockB, waiting to get lockA
And the program has been running a state, then the program out of this situation should be how to troubleshoot it? For the simple case with us directly since you can see where the problem is specific jstack the
Investigation deadlock
The first to use jps view the current process ID program
Then use to print information jstack