Causes of deadlock and ways to avoid deadlock

A deadlock situation

Thread t1 gets the lock and does not release the lock because of some exceptions, and threads t1 and t2 wait for each other to release the lock.

public class DeadLockDemo {
    
    
    private static String A="A";
    private static String B="B";
    public static void main(String[] args) {
    
    
        new DeadLockDemo().deadLock();
    }
    private void deadLock(){
    
    
        Thread t1=new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                synchronized (A){
    
    
                    try {
    
    
                        Thread.currentThread().sleep(2000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    synchronized (B){
    
    
                        System.out.println("1");
                    }
                }
            }
        });
        Thread t2=new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                synchronized (B){
    
    
                    synchronized (A){
    
    
                        System.out.println("2");
                    }
                }
            }
        });
        t1.start();
        t2.start();
    }
}

Common ways to avoid deadlock

  1. Avoid that one thread acquires multiple locks at the same time.
  2. Avoid a thread occupying multiple resources in the lock at the same time, and try to ensure that each lock only occupies the same resource.
  3. Try to use a timing lock, use lock.tryLock(timout) instead of using the internal lock mechanism.
  4. For database locks, locking and unlocking must be in the same database, otherwise unlocking will fail.

Guess you like

Origin blog.csdn.net/weixin_44146509/article/details/108775306
Recommended