和CountDownLatch一样,这也是利用共享模式的AbstractQueuedSynchronizer来进行扩展的功能。
1.覆写的tryAcquireShared方法
/*
* Acquisition succeeds if the future is done, otherwise it fails.
*/
@Override
protected int tryAcquireShared(int ignored) {
if (isDone()) {
return 1;
}
return -1;
}
通过isDone方法判断,如果没有完成,阻塞,可以获得锁。和CountDownLatch类似,后者是判断getState是否是0,state是int型,所以可以有多个状态,对应了多次countDown。
这里isDone返回值是boolean型,所以只有两个状态,完成/没完成。
/**
* Checks if the state is {@link #COMPLETED}, {@link #CANCELLED}, or {@link
* INTERRUPTED}.
*/
boolean isDone() {
return (getState() & (COMPLETED | CANCELLED | INTERRUPTED)) != 0;
}
但实际没完成有多种情况,如代码所示,COMPLETED,CANCELLED和INTERRUPTED都是完成状态,所以只要是这三种状态之一,都表示完成,可以获得锁。
2.覆写的tryReleaseShared
/*
* We always allow a release to go through, this means the state has been
* successfully changed and the result is available.
*/
@Override
protected boolean tryReleaseShared(int finalState) {
setState(finalState);
return true;
}
该方法永远返回true,触发该方法的条件就是调用complete方法中的releaseShared方法。
3.complete方法
/**
* Implementation of completing a task. Either {@code v} or {@code t} will
* be set but not both. The {@code finalState} is the state to change to
* from {@link #RUNNING}. If the state is not in the