2015-01-13 46 views
0

我有一個Executor需要終止,然後我才能關閉另一個Executor,我正在考慮嘗試實施等待通知策略,但通知必須來自executor.isTerminated(),所以除非我繼承它,否則我可以' t通知關閉線程。是否有其他的分類方法,或者等待?如何在等待Executor終止時避免子類化?

+0

聽衆/觀衆模式? –

+1

@HovercraftFullOfEels主題是什麼?如果它是執行者,它仍然聽起來像我不得不繼承它。 –

+0

爲什麼你需要關閉執行程序? – immibis

回答

0

我想也許你想同步終止執行者。我們總是可以用一種變通方法來做到這一點:

//THE LOGIC BEFORE YOU WANT TO WAIT THE EXECUTOR 
... 
executor.shutdown(); 
try { 
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} 
//THE LOGIC AFTER THE EXECUTOR TERMINATION 
... 

使用awaitTermination方法與MAX_VALUE時間。

0
Executor executor = Executors.newFixedThreadPool(YOUR_THREAD_COUNT); 
exector.shutDown(); 

boolean shutdown = false; 
try { 
    shutdown = executor.awaitTermination(YOUR_TIME_OUT, TimeUnit.MILLISECOND); 
} catch (InterruptedException e) { 
    // handle the exception your way 
} 

if (!shutdown) { 
    LOG.error("Executor not shut down before time out."); 
} 
相關問題