Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Created June 24, 2016 06:32
Show Gist options
  • Select an option

  • Save pfmiles/54ebd046bd2d21108ab669716410379d to your computer and use it in GitHub Desktop.

Select an option

Save pfmiles/54ebd046bd2d21108ab669716410379d to your computer and use it in GitHub Desktop.
用于包装某耗时逻辑,并以指定的时等待其执行完毕的工具方法
/**
* 用于包装某耗时逻辑,并以指定的时等待其执行完毕,若未执行完毕则抛出TimeoutException; 若在指定的时间内执行完毕则正常返回
* @param logic 将要执行的耗时逻辑, 注意:该逻辑中的耗时操作必须正确响应interrupt操作, 若不明白这句话含义的请咨询 @pf_miles, 切勿在不明白原理的情形下冒然使用
* @param toWait 期望等待的时间,以ms计
* @throws TimeoutException 超时抛出
*/
public static <R> R timedWaiting(Callable<R> logic, final long toWait) throws TimeoutException,
Exception {
// 原理:主、子线程谁先醒来就interrupt对方
final Thread mainThread = Thread.currentThread();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(toWait);
mainThread.interrupt();// 超时
} catch (InterruptedException e) {
// 执行未超时,正常退出
}
}
}, "Timed-waiting-thread-" + seq.getAndIncrement());
t.start();
R ret = null;
try {
ret = logic.call();
} catch (InterruptedException e) {
// 超时
throw new TimeoutException();
} catch (Exception e) {
throw e;// 业务抛错
} finally {
t.interrupt();// 未超时
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment