[英]How to end a task(timeout a thread) (by rising interrupt) using executor.execute and future.get() without blocking the main thread
[英]Java how to timeout a thread WITHOUT using future.get and without blocking parent thread
我正在尋找使線程執行超時的方法,並找到以下示例: https : //stackoverflow.com/a/16231834/10015830
Future<?> future = service.submit(new MyCallable());
try {
future.get(100, TimeUnit.MILLISECONDS);
} catch (Exception e){
e.printStackTrace();
future.cancel(true); //this method will stop the running underlying task
}
但是我的需要與上面的示例不同:我不希望父線程在future.get
處被阻塞。 換句話說,我不需要獲取可調用對象的結果。 因為在我的實際應用程序中,父線程是定期執行的( scheduled
任務,例如5秒)。
有沒有沒有使用future.get
並且不阻塞父線程的線程超時的方法? (似乎invokeAll
也在阻塞)。
您可以從計時器任務中取消長時間運行的任務:
import java.util.Timer;
import java.util.TimerTask;
Timer timer = new Timer();
Future<?> future = service.submit(new MyCallable());
TimerTask controlTask = new TimerTask(){
@Override
public void run() {
if (!future.isDone()) {
future.cancel(true);
}
}
};
long delay = 100;
timer.schedule(task, delay);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.