上QQ阅读APP看书,第一时间看更新
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所示。线程的个数呈递减的状态。
图1-14 运行结果