是否可以使ScheduledExecutorService具有一个正在运行的任务且只有一个等待任务?
Runnable runnable;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private volatile ScheduledFuture<?> self;
protected void waitAndSweep(final String symbol) {
try {
runnable = new Runnable() {
@Override
public void run() {
try {
long sweepTime = symbolInfo.getSweepTime(symbol);
long timeSinceLastSweep = System.currentTimeMillis() - sweepTime;
long waitTime = timeSinceLastSweep >= getInterval() ? 0 : getInterval() - timeSinceLastSweep;
logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
if (waitTime > 0){
Thread.sleep(waitTime);
}
callSweep(symbol);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
self = scheduler.schedule(runnable,0,TimeUnit.SECONDS);
}catch (Exception e) {
logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
"Exception caught...", e);
}
}
在上面的代码中,假设一个可运行的任务由调度程序调度,它正在等待10s(thread.sleep(time)),在这个休眠时间内,如果调度程序安排了其他任务,它将等待。现在第三个任务进入调度程序,然后调度程序不应该接受它,因为已经有一个正在运行和一个等待任务
答案 0 :(得分:0)
您需要使用ScheduledExecutorService还是ThreadPoolExecutor?如果是这样,您可以通过自己创建(而不是使用Executors.newFixedThreadPool(1))来控制一次排队的任务数量,并为您自己的队列提供如下定义的容量:
var re = /<br>([^<]*>)/gi;
var str = '<span style="font-family:Arial;font-size: 14px;">\n <span class="author-basic">new op\n <span style="font-size: 30px;">tionlab</span> \n </span<br>>';
var subst = '$1<br>';
var result = str.replace(re, subst);
alert(result);
此外,您可以使用Spring框架中的ThreadPoolTaskExecutor类以较少的配置执行此操作:
int oneThread = 1;
long zeroKeepAlive = 0L;
int queueDepthOfOne = 1;
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(
oneThread,
oneThread,
zeroKeepAlive,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(queueDepthOfOne)
);
ThreadPoolTaskExecutor API文档:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.html