![Java并发编程:核心方法与框架](https://wfqqreader-1252317822.image.myqcloud.com/cover/235/822235/b_822235.jpg)
上QQ阅读APP看书,第一时间看更新
![](https://epubservercos.yuewen.com/D3D8F4/4410924203007901/epubprivate/OEBPS/Images/icon1.png?sign=1738887942-LDl252dIK8LVuYta033GiAHUETl9yNah-0-6e4756bba9a51d81ff2c88ab9d9e2c8d)
1.1.6 方法getQueueLength()和hasQueuedThreads()
方法getQueueLength()的作用是取得等待许可的线程个数。
方法hasQueuedThreads()的作用是判断有没有线程在等待这个许可。
这两个方法通常都是在判断当前有没有等待许可的线程信息时使用。
创建测试用的项目twoMethodTest,类MyService.java代码如下:
package myservice; import java.util.concurrent.Semaphore; public class MyService { private Semaphore semaphore = new Semaphore(1); public void testMethod() { try { semaphore.acquire(); Thread.sleep(1000); System.out.println("还有大约" + semaphore.getQueueLength() + "个线程在等待"); System.out.println("是否有线程正在等待信号量呢?" + semaphore. hasQueuedThreads()); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } }
类MyThread.java代码如下:
package extthread; import myservice.MyService; public class MyThread extends Thread { private MyService myService; public MyThread(MyService myService) { super(); this.myService = myService; } @Override public void run() { myService.testMethod(); } }
类Run.java代码如下:
package test.run; import myservice.MyService; import extthread.MyThread; public class Run { public static void main(String[] args) { MyService service = new MyService(); MyThread firstThread = new MyThread(service); firstThread.start(); MyThread[] threadArray = new MyThread[4]; for (int i = 0; i < 4; i++) { threadArray[i] = new MyThread(service); threadArray[i].start(); } } }
程序运行后的效果如图1-14所示。线程的个数呈递减的状态。
![](https://epubservercos.yuewen.com/D3D8F4/4410924203007901/epubprivate/OEBPS/Images/figure_0025_0001.jpg?sign=1738887942-227xL4xYHQi5J9HtbVCjY248SMIqGy2j-0-08f3ecb420fdd6a75119414f1e7449f5)
图1-14 运行结果