3、查看对应condition.await()状态的线程个数 lock.getWaitQueueLength(condition)
import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @ClassName getAwaitCount * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/25. */ public class ReentrantLockgetAwaitCount { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); Runnable r = () -> { lock.lock(); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }; List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { threads.add(new Thread(r)); } threads.forEach(thread -> thread.start()); Thread.sleep(2000); lock.lock(); System.out.println("目前有" + lock.getWaitQueueLength(condition) + "个线程执行了对应的condition的await方法"); //目前有10个线程执行了对应的condition的await方法 condition.signalAll(); System.out.println("目前有" + lock.getWaitQueueLength(condition) + "个线程执行了对应的condition的await方法"); //目前有0个线程执行了对应的condition的await方法 lock.unlock(); } }
4、判断某个线程是否正在等待该锁 lock.hasQueuedThread(t2)
示例代码:
import java.util.concurrent.locks.ReentrantLock; /** * @ClassName ReentrantLockWaitLockOrNot * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/25. */ public class ReentrantLockWaitLockOrNot { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Runnable r = () -> { lock.lock(); try { Thread.sleep(Integer.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }; Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); Thread.sleep(1000); t2.start(); Thread.sleep(1000); System.out.println(lock.hasQueuedThread(t2)); //true } }
5、判断是否有线程在对应锁的waiter暂停状态中 lock.hasWaiters(condition)
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @ClassName ReentrantLockHasWaiters * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/25. */ public class ReentrantLockHasWaiters { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Condition condition = lock.newCondition(); Runnable r = () -> { lock.lock(); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }; Thread t1 = new Thread(r); t1.start(); Thread.sleep(1000); lock.lock(); System.out.println(lock.hasWaiters(condition)); //true condition.signal(); Thread.sleep(1000); System.out.println(lock.hasWaiters(condition)); //false lock.unlock(); } }