Semaphore,等待指定数量的线程完成任务。常用做线程限流或者推测执行机制。(一个大任务,多个机器执行,谁先执行完就采用谁的计算结果)。
acquire()方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
release()方法
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
//信号量的许可数 = 当前信号许可数 + 待释放的信号许可数
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
//设置可获取的信号许可数为next
if (compareAndSetState(current, next))
return true;
}
}
代码示例:
public class SpeculationComputeDemo {
public static void main(String[] args) throws Exception {
Semaphore semaphore = new Semaphore(0);
for(int i = 0; i < 3; i++) {
new Thread() {
public void run() {
try {
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
System.out.println(Thread.currentThread() + "分配同一个计算任务给不同的机器......");
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
semaphore.acquire(1);
System.out.println("一台机器已经先执行成功了,此时就可以收拢计算结果了");
}
}