3.死锁

避免死的几个常方法 

  1. 避免一个线程同时获取多个锁 
  2. 尽量保每个只占用一个源 
  3. 尝试使用定时锁,使用lock.tryLocktimeout)来替代使用内部机制 
  4. 于数据库锁,加和解在一个数据库连接里 

 

一个死锁的例子

public class DeadLockDemo {
  privat 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       publicvoid 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       publicvoid run() {         synchronized (B) {           synchronized (A) {             System.out.println("2");           }         }       }     });     t1.start();     t2.start();   } }

 

在一些更为复景:t1拿到之后,因一些异常情况没有锁(死循)。又或者是t1拿到一个数据库锁候抛出了异常,没放掉。


dump线看到底是哪个线程出问题,以下线程信息告DeadLockDemo的第42行和第31行引起的死锁 


"Thread-2" prio=5 tid=7fc0458d1000 nid=0x116c1c000 waiting for monitor entry [116c1b000java.lang.Thread.State: BLOCKED (on object monitor)
  at com.ifeve.book.forkjoin.DeadLockDemo$2.run(DeadLockDemo.java:42)
  - waiting to lock <7fb2f3ec0> (a java.lang.String)
  - locked <7fb2f3ef8> (a java.lang.String)
  at java.lang.Thread.run(Thread.java:695)
"Thread-1" prio=5 tid=7fc0430f6800 nid=0x116b19000 waiting for monitor entry [116b18000java.lang.Thread.State: BLOCKED (on object monitor)
  at com.ifeve.book.forkjoin.DeadLockDemo$1.run(DeadLockDemo.java:31)
  - waiting to lock <7fb2f3ef8> (a java.lang.String)
  - locked <7fb2f3ec0> (a java.lang.String)
  at java.lang.Thread.run(Thread.java:695)
 

 

posted on 2017-02-20 16:00  近博  阅读(232)  评论(0编辑  收藏  举报

导航