[英]Issue in Future.cancel() method
我有一個下面的可運行任務,該任務通過使用ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
這樣可以確保隊列中只有一個等待任務。
protected void waitAndSweep(final String symbol) {
try {
runnable = new Runnable() {
@Override
public void run() {
try {
// long sweepTime = symbolInfo.getSweepTime(symbol);
// long timeSinceLastSweep = System.currentTimeMillis() - lastSliceSentTime;
boolean sliceDone = Quant.equals(wave.getCommitedQuantity() % getSliceQuantity(),0);
if(sliceDone){
long timeSinceLastSliceQtySent = lastSliceSentTime == 0 ? getInterval() : System.currentTimeMillis() - lastSliceSentTime;
long waitTime = timeSinceLastSliceQtySent >= getInterval() ? 0 : getInterval() - timeSinceLastSliceQtySent;
logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
if (waitTime > 0){
Thread.sleep(waitTime);
}
}
callSweep(symbol);
} catch(InterruptedException ie){
ie.printStackTrace();
}
catch (Exception e) {
logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
"Exception caught...", e);
}
}
};
self = threadPoolExecutor.submit(runnable);
}catch(RejectedExecutionException re){
/* this exception will be thrown when wait and sweep is called more than twice.
* threadPoolExecutor can have one running task and one waiting task.
* */
System.out.print(re);
}catch (Exception e) {
logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
"Exception caught...", e);
}
}
考慮呼叫者A:
private void callerA(){
waitandsweep();
waitandsweep();}
這引發了兩項任務,一項正在運行,另一項在隊列中等待。
考慮呼叫者B:
private void callerB(){
self.cancel(true);
waitandsweep();}
期望調用者B取消A調用的所有任務。實際上,它沒有發生。調用者B調用的任務被拒絕了,因為隊列中已經有一個任務在等待。 你能告訴我為什么會發生這種情況嗎?
編輯1:如何取消執行程序的運行任務?
問題在於, Future.cancel(boolean)
不會從隊列中刪除任務。 該任務將不會被執行,一旦將被拉到Executor
在隊列但在那之前它仍然
嘗試使用threadPoolExecutor.purge();
在cancel();
它將嘗試刪除已取消的任務
取消正在運行的Task並不容易,您可以嘗試執行以下操作:調用cancel(true);
它將Thread.interrupted()
設置為true
。 現在,在“任務”中檢查有價值的一些步驟,因此您可以決定跳過任務的后續步驟
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.