我正在嘗試編寫一個方法來創(chuàng)建一個線程,該線程在該方法已經(jīng)返回后可以工作。我需要這個線程在一定時間后超時。我有一個可行的解決方案,但我不確定這是否是最好的方法。 new Thread(() -> { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable() { public Void call() throws Exception { workThatTakesALongTime(); }); try { future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { LOGGER.error("Exception from timeout.", e); } }).start();有沒有更好的方法來做到這一點而不使用線程中的 ExecutorService ?
2 回答

函數(shù)式編程
TA貢獻(xiàn)1807條經(jīng)驗 獲得超9個贊
有多種方法可以實現(xiàn)這一點。正如您所做的那樣,一種方法是使用 ExecutorService。一個更簡單的方法是創(chuàng)建一個新線程和一個隊列,如果每隔幾秒就有一些東西,線程就會從中查找。一個例子是這樣的:
Queue<Integer> tasks = new ConcurrentLinkedQueue<>();
new Thread(){
public void run() throws Exception {
while(true){
Integer task = null;
if((task = tasks.poll()) != null){
// do whatever you want
}
Thread.sleep(1000L); // we probably do not have to check for a change that often
}
}
}.start();
// add tasks
tasks.add(0);
添加回答
舉報
0/150
提交
取消