package com.fh.interview; /** * @author 死锁测试 * @create 2018-05-27 下午2:26 **/ public class DeadLockDemo { public static String resourceA = "A"; public static String resourceB = "B"; public static void main(String[] args) { deadLock(); } public static void deadLock(){ Thread threadA = new Thread(new Runnable() { public void run() { synchronized (resourceA){ System.out.println("lock resourceA"); try { Thread.sleep(3000); synchronized (resourceB){ System.out.println("lock resourceB"); } }catch (Exception e){ e.printStackTrace(); } } } },"threadA"); Thread threadB = new Thread(new Runnable() { public void run() { synchronized (resourceB){ System.out.println("lock resourceB"); synchronized (resourceA){ System.out.println("lock resourceA"); } } } },"threadB"); threadA.start(); threadB.start(); } }
可以使用jps查看进程ID
使用 jstack pid 查看进程内的线程状态
- 避免一个线程同时获得多个锁;
- 避免一个线程在锁内部占有多个资源,尽量保证每个锁只占用一个资源;
- 尝试使用定时锁,使用lock.tryLock(timeOut),当超时等待时当前线程不会阻塞;
- 对于数据库锁,加锁和解锁必须在一个数据库连接里,否则会出现解锁失败的情况