com.yixan.tools.common.wait.WaitLocks Maven / Gradle / Ivy
package com.yixan.tools.common.wait;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeoutException;
import com.yixan.tools.common.wait.WaitLock.Checker;
/**
* 等待结果
*
* @author zhaohuihua
* @version V1.0 2017年4月6日
*/
public class WaitLocks {
protected List> waiters;
public WaitLocks() {
this.waiters = new Vector<>();
}
/**
* 等待结果
*
* @param clazz 结果的类型
* @param time 超时时间
* @return 结果
* @throws TimeoutException
*/
public T await(Class extends T> clazz, long time) throws TimeoutException {
return this.await(new WaitLock(clazz), time);
}
/**
* 等待结果
*
* @param checker 检查结果的检查器
* @param time 超时时间
* @return 结果
* @throws TimeoutException
*/
public T await(Checker checker, long time) throws TimeoutException {
return this.await(new WaitLock(checker), time);
}
protected T await(WaitLock waiter, long time) throws TimeoutException {
this.waiters.add(waiter);
try {
return waiter.await(time);
} finally {
this.waiters.remove(waiter);
}
}
/**
* 尝试通知, 如果检查通过则通知等待者
*
* @param result 结果
*/
public void trySignal(Object result) {
synchronized (waiters) {
Iterator> iterator = waiters.iterator();
while (iterator.hasNext()) {
WaitLock> i = iterator.next();
i.trySignal(result);
}
}
}
public int size() {
return this.waiters.size();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy