Java多线程实战:深入理解Lock与ReentrantLock的区别与应用
最编程
2024-07-28 18:06:08
...
package com.szh.lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用 tryLock() 可以避免死锁
*/
public class Test09 {
static class MyLock implements Runnable {
private static ReentrantLock lock1=new ReentrantLock();
private static ReentrantLock lock2=new ReentrantLock();
private int lockNum;
public MyLock(int lockNum) {
this.lockNum=lockNum;
}
@Override
public void run() {
if (lockNum % 2 == 0) { //偶数先锁 1, 再锁 2
while (true) {
try {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "获得了锁1,还想获得锁2");
Thread.sleep(50);
try {
if (lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2,完成任务了");
return;
}
} finally {
if (lock2.isHeldByCurrentThread()) {
lock2.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock1.isHeldByCurrentThread()) {
lock1.unlock();
}
}
}
}else { //奇数就先锁 2, 再锁 1
while (true) {
try {
if (lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + "获得了锁2,还想获得锁1");
Thread.sleep(50);
try {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2,完成任务了");
return;
}
} finally {
if (lock1.isHeldByCurrentThread()) {
lock1.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock2.isHeldByCurrentThread()) {
lock2.unlock();
}
}
}
}
}
}
public static void main(String[] args) {
MyLock lock1=new MyLock(11);
MyLock lock2=new MyLock(22);
Thread t1=new Thread(lock1);
Thread t2=new Thread(lock2);
t1.start();
t2.start();
//运行后, 使用 tryLock() 尝试获得锁, 不会傻傻的等待, 通过循环不停的再次尝试, 如果等待的时间足够长, 线程总是会获得想要的资源
}
}
推荐阅读
-
深入理解分治算法在LeetCode实战中的应用:快速排序思维解析与算法沉淀
-
实战技巧:深入理解与学习Tair缓存的高级应用笔记
-
理解Java ReentrantLock中的tryLock与lock差异:聚焦公平锁与非公平锁的实战解析
-
深入理解Java中Lock和tryLock方法的工作原理与应用
-
在Java中,理解锁方法(Lock): lock与tryLock的实战运用
-
深入理解Java源码:ReentrantLock的lockInterruptibly与tryLock方法剖析
-
深入理解Java多线程中tryLock方法的运用与实践
-
深入理解Java多线程中tryLock方法的运用与实践
-
深入理解Java锁接口(Lock)的工作机制与实战示例
-
深入理解Java中ReentrantLock的实现与用法详解