Java 死锁及解决方法

死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止。
java 死锁产生的四个必要条件:
  • 1>互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
  • 2>不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
  • 3>请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的战友。
  • 4>循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。下面用java代码来模拟一下死锁的产生。
解决死锁问题的方法是:一种是用synchronized,一种是用Lock显式锁实现。
而如果不恰当的使用了锁,且出现同时要锁多个对象时,会出现死锁情况,如下:
import java.util.Date;

public class LockTest {
   public static String obj1 = "obj1";
   public static String obj2 = "obj2";
   public static void main(String[] args) {
      LockA la = new LockA();
      new Thread(la).start();
      LockB lb = new LockB();
      new Thread(lb).start();
   }
}
class LockA implements Runnable{
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockA 开始执行");
         while(true){
            synchronized (LockTest.obj1) {
               System.out.println(new Date().toString() + " LockA 锁住 obj1");
               Thread.sleep(3000); // 此处等待是给B能锁住机会
               synchronized (LockTest.obj2) {
                  System.out.println(new Date().toString() + " LockA 锁住 obj2");
                  Thread.sleep(60 * 1000); // 为测试,占用了就不放
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
class LockB implements Runnable{
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockB 开始执行");
         while(true){
            synchronized (LockTest.obj2) {
               System.out.println(new Date().toString() + " LockB 锁住 obj2");
               Thread.sleep(3000); // 此处等待是给A能锁住机会
               synchronized (LockTest.obj1) {
                  System.out.println(new Date().toString() + " LockB 锁住 obj1");
                  Thread.sleep(60 * 1000); // 为测试,占用了就不放
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
运行结果:
Tue May 05 10:51:06 CST 2015 LockB 开始执行
Tue May 05 10:51:06 CST 2015 LockA 开始执行
Tue May 05 10:51:06 CST 2015 LockB 锁住 obj2
Tue May 05 10:51:06 CST 2015 LockA 锁住 obj1

  

此时死锁产生。
为了解决这个问题,我们不使用显示的去锁,我们用信号量去控制。
信号量可以控制资源能被多少线程访问,这里我们指定只能被一个线程访问,就做到了类似锁住。而信号量可以指定去获取的超时时间,我们可以根据这个超时时间,去做一个额外处理。
对于无法成功获取的情况,一般就是重复尝试,或指定尝试的次数,也可以马上退出。
来看下如下代码:
import java.util.Date;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class UnLockTest {
   public static String obj1 = "obj1";
   public static final Semaphore a1 = new Semaphore(1);
   public static String obj2 = "obj2";
   public static final Semaphore a2 = new Semaphore(1);

   public static void main(String[] args) {
      LockAa la = new LockAa();
      new Thread(la).start();
      LockBb lb = new LockBb();
      new Thread(lb).start();
   }
}
class LockAa implements Runnable {
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockA 开始执行");
         while (true) {
            if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + " LockA 锁住 obj1");
               if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + " LockA 锁住 obj2");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockA 锁 obj2 失败");
               }
            }else{
               System.out.println(new Date().toString() + "LockA 锁 obj1 失败");
            }
            UnLockTest.a1.release(); // 释放
            UnLockTest.a2.release();
            Thread.sleep(1000); // 马上进行尝试,现实情况下do something是不确定的
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
class LockBb implements Runnable {
   public void run() {
      try {
         System.out.println(new Date().toString() + " LockB 开始执行");
         while (true) {
            if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
               System.out.println(new Date().toString() + " LockB 锁住 obj2");
               if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
                  System.out.println(new Date().toString() + " LockB 锁住 obj1");
                  Thread.sleep(60 * 1000); // do something
               }else{
                  System.out.println(new Date().toString() + "LockB 锁 obj1 失败");
               }
            }else{
               System.out.println(new Date().toString() + "LockB 锁 obj2 失败");
            }
            UnLockTest.a1.release(); // 释放
            UnLockTest.a2.release();
            Thread.sleep(10 * 1000); // 这里只是为了演示,所以tryAcquire只用1秒,而且B要给A让出能执行的时间,否则两个永远是死锁
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

 

运行结果:
Tue May 05 10:59:13 CST 2015 LockA 开始执行
Tue May 05 10:59:13 CST 2015 LockB 开始执行
Tue May 05 10:59:13 CST 2015 LockB 锁住 obj2
Tue May 05 10:59:13 CST 2015 LockA 锁住 obj1
Tue May 05 10:59:14 CST 2015LockB 锁 obj1 失败
Tue May 05 10:59:14 CST 2015LockA 锁 obj2 失败
Tue May 05 10:59:15 CST 2015 LockA 锁住 obj1
Tue May 05 10:59:15 CST 2015 LockA 锁住 obj2

 

采用lock锁 使用trylock 获取锁,并使用unlock释放锁 采用flag控制循环的结束
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description  采用lock 锁 使用trylock 获取锁,并使用unlock释放锁 采用flag控制循环的结束
 **/
public class LockTest3 {
    
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new LockA(),"线程A");
        Thread t2 = new Thread(new LockB(),"线程B");

        t1.start();
        t2.start();
        Thread.sleep(5000);
        System.out.println("主线程结束");
    }

    static class LockA implements Runnable{

        boolean fa = true;
        @Override
        public void run() {
            System.out.println("线程A开始执行"+new Date());
            try {
                while (fa){
                    if (LockTest3.lock1.tryLock(1,TimeUnit.SECONDS)){
                        System.out.println("线程A锁住lock1"+new Date());
                        if (LockTest3.lock2.tryLock(1,TimeUnit.SECONDS)){
                            System.out.println("线程A锁住lock2"+new Date());
                            fa =false;
                        }else {
                            System.out.println("线程A锁住lock2 失败"+new Date());
                        }
                    }else {
                        System.out.println("线程A锁住lock1 失败"+new Date());
                    }

                  /*  lock1.unlock();
                    lock2.unlock();*/
                    System.out.println("当前线程"+Thread.currentThread().getName());
                    if (lock1.isHeldByCurrentThread()){
                        lock1.unlock();
                        System.out.println("线程A释放lock1");
                    }
                    if (lock2.isHeldByCurrentThread()){
                        lock2.unlock();
                        System.out.println("线程A释放lock2");
                    }
                    Thread.sleep(2000);
                }
                System.out.println("线程A结束=============");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class LockB implements Runnable{
        boolean fb = true;

        @Override
        public void run() {
            System.out.println("线程B开始执行"+new Date());
            try {
                while (fb){
                    if (LockTest3.lock2.tryLock(1,TimeUnit.SECONDS)){
                        System.out.println("线程B锁住lock2"+new Date());
                        if (LockTest3.lock1.tryLock(1,TimeUnit.SECONDS)){
                            System.out.println("线程B锁住lock1"+new Date());
                            fb=false;
                        }else {
                            System.out.println("线程B锁住lock1 失败"+new Date());
                        }
                    }else {
                        System.out.println("线程B锁住lock2 失败"+new Date());
                    }
                /*    lock1.unlock();
                    lock2.unlock();*/
                    System.out.println("当前线程"+Thread.currentThread().getName());
                    if (lock1.isHeldByCurrentThread()){
                        lock1.unlock();
                        System.out.println("线程B释放lock1");
                    }
                    if (lock2.isHeldByCurrentThread()){
                        lock2.unlock();
                        System.out.println("线程B释放lock2");
                    }
                    Thread.sleep(2000);
                }
                System.out.println("线程结束B=============");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}  

 输出结果

线程A开始执行Wed Dec 25 11:23:27 CST 2019
线程A锁住lock1Wed Dec 25 11:23:27 CST 2019
线程A锁住lock2Wed Dec 25 11:23:27 CST 2019
当前线程线程A
线程A释放lock1
线程A释放lock2
线程B开始执行Wed Dec 25 11:23:27 CST 2019
线程B锁住lock2Wed Dec 25 11:23:27 CST 2019
线程B锁住lock1Wed Dec 25 11:23:27 CST 2019
当前线程线程B
线程B释放lock1
线程B释放lock2
线程A结束=============
线程结束B=============
主线程结束

  

 

 

  

posted @ 2019-12-24 20:09  Andrew_F  阅读(2467)  评论(0编辑  收藏  举报