• 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)
     

  • 相关阅读:
    HDU 1847 Good Luck in CET-4 Everybody!(博弈、找规律)
    HDU 1564 Play a game(博弈、找规律)
    HDU 2188 悼念512汶川大地震遇难同胞——选拔志愿者(巴什博弈)
    HDU 2516 取石子游戏(斐波那契博弈)
    HDU 1517 A Multiplication Game(博弈)
    HDU
    POJ-1182 食物链(并查集)
    POJ-1915 Knight Moves (BFS)
    python模块详解 time与date time
    python模块介绍和 import本质
  • 原文地址:https://www.cnblogs.com/jimboi/p/6419960.html
Copyright © 2020-2023  润新知