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

如何运用tryLock功能

最编程 2024-07-28 19:42:15
...
public static void main(String[] args) { ReentrantLock lock = new ReentrantLock(); new Thread(() -> { if (lock.tryLock()) { System.out.println("A拿到锁了"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } else { System.out.println("A没有拿到锁"); } }, "MyThread-A").start(); new Thread(() -> { if (lock.tryLock()) { System.out.println("B拿到锁了"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } else { System.out.println("B没有拿到锁"); } }, "MyThread-B").start(); }