Java code using handwritten deadlock

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

 

 

From the above you can see two threads are block themselves to live and look at the code error analysis

How to prevent deadlock

Deadlock of a headache, then how to prevent deadlock it?

Deadlock prevention of conditions must first know Deadlock

1. mutex (a resource can only be accessed by one process)

2. Request and hold (when a resource request due process blocked, no release of its own resources)

3. Inalienable (resource process has been, and can not be preempted deprivation)

4. Wait loop (loop is formed waiting for the relationship between the process)

So long as we destroy one of them will not produce a deadlock.

Prevention methods are:

1. The famous banker's algorithm

tryLock (long timeout, TmeUnit unit) 2. The method can be used with Time

3. Avoid the use of a plurality of locks

......

Guess you like

Origin www.cnblogs.com/lgxblog/p/11691506.html