转自:
下文笔者讲述工作中避免死锁的方法分享,如下所示:
1.设置超时时间
Lock的tryLock(Long timeout,TimeUnit unit) 设置获取锁的时间,如果达到这个时间还没有获取到锁,就回退 synchronized 不具备尝试锁的能力 获取不到锁的,也就是获取失败,我们进行日志记录,邮件提醒,重启服务器
/**
* 用tryLock来避免死锁
*/
public class TryLockDeadlock implements Runnable{
int flag = 1;
static Lock lock1 = new ReentrantLock();
static Lock lock2 = new ReentrantLock();
public static void main(String[] args) {
TryLockDeadlock deadlock1 = new TryLockDeadlock();
TryLockDeadlock deadlock2 = new TryLockDeadlock();
deadlock1.flag = 1;
deadlock1.flag = 0;
new Thread(deadlock1).start();
new Thread(deadlock2).start();
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {