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

1.1.8 方法tryAcquire()的使用
无参方法tryAcquire()的作用是尝试地获得1个许可,如果获取不到则返回false,此方法通常与if语句结合使用,其具有无阻塞的特点。无阻塞的特点可以使线程不至于在同步处一直持续等待的状态,如果if语句判断不成立则线程会继续走else语句,程序会继续向下运行。
创建Java项目Semaphore_tryAcquire_1,类代码如下:
package service; import java.util.concurrent.Semaphore; public class Service { private Semaphore semaphore = new Semaphore(1); public void testMethod() { if (semaphore.tryAcquire()) { 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() + "未成功进入!"); } } }
两个线程类如图1-17所示。

图1-17 线程类代码
运行类Run.java代码如下:
package test.run; import service.Service; import extthread.ThreadA; import extthread.ThreadB; public class Run { public static void main(String[] args) { Service service = new Service(); ThreadA a = new ThreadA(service); a.setName("A"); a.start(); ThreadB b = new ThreadB(service); b.setName("B"); b.start(); } }
程序运行后的效果如图1-18所示。

图1-18 线程B未获得许可