是一种计数器,用来保护一个或者多个共享资源的访问。java
Semaphore.acquire()
//获取信号量,,当信号量的内部计数器变成0的时候,信号量将阻塞线程直到其被释放。若是阻塞期间被中断会抛出异常ui
Semaphore.acquireUninterruptibly();
//获取信号量,当信号量的内部计数器变成0的时候,信号量将阻塞线程直到其被释放。若是阻塞期间被中断不会抛出异常this
Semaphore.release() //释放信号量线程
Semaphore.tryAcquire() //试图获取信号量,若是能获取就返回true,不能就返回falsecode
Semaphore semaphore = new Semaphore(1, true); 建立信号量,计数器值为1,且是公平模式资源
Semaphore semaphore = new Semaphore(1, false); 建立信号量,计数器值为1,且是非公平模式it
static class Printer { private final Semaphore semaphore; Printer(Semaphore semaphore) { this.semaphore = semaphore; } public void print(String text) { try { this.semaphore.acquire(); TimeUnit.SECONDS.sleep(1); System.out.println(text); TimeUnit.SECONDS.sleep(1); System.out.println(text); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } finally { this.semaphore.release(); } } } public static void main(String[] args) { Semaphore semaphore = new Semaphore(1, true); Stream.of("aaa", "bbb", "ccc").forEach(text -> { new Thread(() -> { Printer printer = new Printer(semaphore); printer.print(text); }).start(); }); }