import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Example { private static Lock lock = new ReentrantLock(); public static void main(String[] args) { if(lock.tryLock()) { try { // Code that requires exclusive access to a resource } finally { lock.unlock(); } } else { // Code to handle the case where the lock cannot be acquired } } }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Example { private static Lock lock1 = new ReentrantLock(); private static Lock lock2 = new ReentrantLock(); public static void main(String[] args) { boolean acquiredLock1 = false; boolean acquiredLock2 = false; try { acquiredLock1 = lock1.tryLock(); acquiredLock2 = lock2.tryLock(); } finally { if(!(acquiredLock1 && acquiredLock2)) { if(acquiredLock1) lock1.unlock(); if(acquiredLock2) lock2.unlock(); } } if(acquiredLock1 && acquiredLock2) { try { // Code that requires access to both resources } finally { lock1.unlock(); lock2.unlock(); } } else { // Code to handle the case where one or both locks cannot be acquired } } }In this example, we have 2 locks that we need to acquire to execute some code that requires access to both resources. We first attempt to acquire both locks using the tryLock() method. If one or both locks cannot be acquired, we release any locks that we've acquired and handle the case accordingly. Otherwise, we execute the code that requires access to both resources and release the locks once we're done.