1. 概述
Semaphore 共享锁,运行多个线程同时临界区
2. 主要接口
public void acquire()
public void acquireUninterruptibly()
public boolean tryAcquire()
public boolean tryAcquire(long timeout, TimeUnit unit)
public void release()
3. 程序实例
package com.john.learn.high.concurent.ch03;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo implements Runnable {
private final Semaphore semaphore = new Semaphore(5);
public void run() {
try {
semaphore.acquire(2);
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " done!");
} catch (InterruptedException e) {
} finally {
semaphore.release(2);
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
for (int i = 0; i < 10; i++) {
executorService.submit(semaphoreDemo);
}
executorService.shutdown();
}
}
两个两个输出。两个进入后,lock=4, 总许可=5.