我們有一個計劃任務,每10秒運行一個線程池,其中包含3個線程,可以實際更新靜態通用映射。計劃的操作每10秒鐘打印一次該地圖。 問題是我希望計劃程序在3個線程完成地圖後停止打印。但這裏是關鍵。我不想立即停止調度程序,我想先打印(地圖的最終版本),然後完成。進行預定的調用以運行一次更多時間
public class myClass implements ThreadListener {
public static ArrayList<Pair<String, Integer>> wordOccurenceSet = new ArrayList<Pair<String, Integer>>();
int numberOfThreads = 0;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void getAnswer(Collection<CharacterReader> characterReaders, Outputter outputter) {
ExecutorService executor = Executors.newFixedThreadPool(characterReaders.size());
OutputterWriteBatch scheduledThread = new OutputterWriteBatch(outputter,wordOccurenceSet);
scheduler.scheduleAtFixedRate(scheduledThread, 10, 10, TimeUnit.SECONDS);
for (CharacterReader characterReader : characterReaders) {
NotifyingRunnable runnable = new CharacterReaderTask(characterReader, wordOccurenceSet);
runnable.addListener(this);
executor.execute(runnable);
}
}
@Override
public void notifyRunnableComplete(Runnable runnable) {
numberOfThreads += 1;
if(numberOfThreads == 3){
//All threads finished... What can I do to terminate after one more run?
}
}
}
Listener實際上只是在線程完成時得到通知。