java避免死锁的方法
程序员文章站
2022-03-26 20:59:23
避免死锁最好的办法,就是避免锁的交叉使用,在已经拥有锁的情况下,尽可能不要去申请别的锁如果一定要这样做,可以使用Lock.tryLock()方法避免死锁public class DeadLockTest { public static final Lock lock1 = new ReentrantLock(); public static final Lock lock2 = new ReentrantLock(); public static void main(Str....
- 避免死锁最好的办法,就是避免锁的交叉使用,在已经拥有锁的情况下,尽可能不要去申请别的锁
如果一定要这样做,可以使用Lock.tryLock()方法避免死锁
public class DeadLockTest {
public static final Lock lock1 = new ReentrantLock();
public static final Lock lock2 = new ReentrantLock();
public static void main(String[] args) {
DeadLockTest test = new DeadLockTest();
Worker worker1 = test.new Worker(lock1, lock2);
Worker worker2 = test.new Worker(lock2, lock1);
worker1.start();
worker2.start();
}
class Worker extends Thread {
public Lock lock1;
public Lock lock2;
public Worker(Lock lock1, Lock lock2) {
this.lock1 = lock1;
this.lock2 = lock2;
}
@SneakyThrows
@Override
public void run() {
if (lock1.tryLock(2, TimeUnit.SECONDS)) {
try {
System.out.println(Thread.currentThread().getName() + "获取了锁:" + lock1);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lock2.tryLock(4, TimeUnit.SECONDS)) {
try {
System.out.println(Thread.currentThread().getName() + "获取了锁:" + lock2);
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + "解锁:" + lock2);
}
} else {
System.out.println("获取锁失败:" + lock2);
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + "解锁:" + lock1);
}
} else {
System.out.println("获取锁失败:" + lock1);
}
}
}
}
本文地址:https://blog.csdn.net/qq_33746216/article/details/107348020
上一篇: 天津大学王牌专业排名 建筑学上榜(4个)
下一篇: Java入门——字符串中的数据排序