import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * Semaphore 信号灯 * * Semaphore通常用于限制可以访问的某一个资源(物理或逻辑)的线程数目,例如实现对文件并发量的访问控制 * 每一个行动在acquire获得一个许可,release放开一个许可 * * 构造方法 * new Semaphore(4) 四个许可 * new Semaphore(4,ture/false) 后面的参数确定抢占许可的策略是否是公平的,默认是false,先来先得 * * 其他应用 * 单个的信号灯可实现线程互斥锁功能,优点是一个线程获得了“锁”,在由另外一个线程释放锁 * 可使用于死锁恢复的一些场合 * * @author * */ public class SemaphoreTest { public static void main(String[] args) { final Semaphore semaphore = new Semaphore(3); ExecutorService service = Executors.newCachedThreadPool(); // 可变的线程池大小 for (int i = 0; i < 10; i++) { Runnable runnable = new Runnable() { @Override public void run() { try { semaphore.acquire(); // 拿走一个许可 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程" + Thread.currentThread().getName() + "拿走 一个许可, 当前还剩"+(3-semaphore.availablePermits())+"个并发"); try { Thread.sleep(new Random().nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程" + Thread.currentThread().getName() + ",即将退出"); semaphore.release(); // 换回 System.out.println("线程" + Thread.currentThread().getName() + ",退出,当前剩余"+(3-semaphore.availablePermits())+"个并发"); } }; service.execute(runnable); } service.shutdown(); } }