
上QQ阅读APP看书,第一时间看更新

1.1.10 方法tryAcquire(long timeout, TimeUnit unit)的使用
有参方法tryAcquire(int long timeout, TimeUnit unit)的作用是在指定的时间内尝试地获得1个许可,如果获取不到则返回false。
创建Java项目Semaphore_tryAcquire_3,将项目Semaphore_tryAcquire_2中的源代码复制到Semaphore_tryAcquire_3中,更改类代码如下:
package service; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class Service { private Semaphore semaphore = new Semaphore(1); public void testMethod() { try { if (semaphore.tryAcquire(3, TimeUnit.SECONDS)) { System.out.println("ThreadName=" + Thread.currentThread().getName() + "首选进入!"); for (int i = 0; i < Integer.MAX_VALUE; i++) { String newString = new String(); Math.random(); } semaphore.release(); } else{ System.out.println("ThreadName=" + Thread.currentThread().getName() + "未成功进入!"); } //方法release对应的permits值也要更改 } catch (InterruptedException e) { e.printStackTrace(); } } }
程序运行后的效果如图1-20所示。

图1-20 线程B未获得许可
更改Service.java类代码如下:
for (int i = 0; i < Integer.MAX_VALUE; i++) { //String newString = new String(); //Math.random(); }
程序运行结果如图1-21所示。

图1-21 双双获得许可