- 关于Semaphore: https://zhuanlan.zhihu.com/p/98593407
- 记录一种实用场景:在规定时间内监控广播后取消注册广播
final Semaphore semaphore = new Semaphore(0);
BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
@Overridepublic void onReceive(Context context, Intent intent) {
semaphore.release();}
}
context.registerReceiver(myBroadcastReceiver, "test");try {
semaphore.tryAcquire(3000, TimeUnit.MILLISECONDS);} catch (InterruptedException e) {
Log.e(TAG, e);}
context.unregisterReceiver(myBroadcastReceiver);
- 这样就可以达到一个目的:在3秒内如果接收到广播,信号量会释放,然后取消注册广播;3秒内没有接收到广播,则触发信号量超时,取消注册广播。