欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

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() 尝试获得锁, 不会傻傻的等待, 通过循环不停的再次尝试, 如果等待的时间足够长, 线程总是会获得想要的资源 } }