我有問題,使用線程將一些電子郵件複製到其他文件夾,我的問題是,代碼不要等待完成工作。使用線程將問題郵件複製到javamail中的文件夾
我想通過線程移動消息來加速工作,但我需要等待移動所有消息,那麼我該怎麼做?
private static void moveMessagesToFolders(List<Message> listMessages, Store store, Set<String> setSender) throws MessagingException {
HashMap<String, List<Message>> mapMessages = separeteMessagesBySender(listMessages, setSender);
for (Entry<String, List<Message>> mapMessage : mapMessages.entrySet()) {
Message[] messageArray = mapMessage.getValue().toArray(new Message[mapMessage.getValue().size()]);
moveMessagesThread(messageArray, mapMessage, store);
}
}
private static void moveMessagesThread(Message[] messageArray, Entry<String, List<Message>> mapMessage, Store store) {
Set<Thread> setThread = createMovimentSetThread(messageArray, mapMessage, store);
for (Thread thread : setThread) {
thread.start();
}
}
private static Set<Thread> createMovimentSetThread(Message[] messageArray, Entry<String, List<Message>> mapMessage, Store store) {
int [] threadIndexs = MathUtil.generateIndex(messageArray);
Set<Thread> setThread = new HashSet<>(threadIndexs.length);
for (int i = 0; i < threadIndexs.length; i++) {
setThread.add(new ThreadMoveMessages(messageArray, mapMessage, store, threadIndexs[i]));
}
return setThread;
}
當我將方法更改爲此實現的執行程序。
private static void moveMessagesThread(Message[] messageArray, Entry<String, List<Message>> mapMessage, Store store) {
int [] threadIndexs = MathUtil.generateIndex(messageArray);
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
executor.execute(new ThreadMoveMessages(messageArray, mapMessage, store, threadIndexs[i]));
}
executor.shutdown();
}
實施Thread類
public class ThreadMoveMessages implements Callable<Boolean> {
private Entry<String, List<Message>> mapMessage;
private Store store;
private Message[] messageArray;
private static int indexControler;
private static int indexLimit;
public ThreadMoveMessages(Message[] messageArray, Entry<String, List<Message>> mapMessage, Store store, int indexEnd) {
this.messageArray = Arrays.copyOf(messageArray, indexEnd);
this.indexControler += indexEnd;
this.indexLimit = indexControler;
this.mapMessage = mapMessage;
}
@Override
public Boolean call() throws Exception {
Folder folder = null;
try {
folder = this.store.getDefaultFolder().getFolder(this.mapMessage.getKey());
folder.open(Folder.READ_WRITE);
folder.appendMessages(this.messageArray);
EmailUtil.deleteListMessage(this.mapMessage.getValue());
} catch (MessagingException e) {
e.printStackTrace();
}
return true;
}
}
考慮使用[執行人(http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ Executor.html)而不是直接管理線程池。 –
@SzymonBiliński我正在閱讀有關'執行者',我感到困惑,因爲我需要做什麼? 我發現人們正在實施新課程或使用單一方法 –
您應該從[基礎知識](http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html)開始閱讀[這](http://stackoverflow.com/questions/3269445/executorservice-how-to-wait-for-all-tasks-to-finish)(等待所有任務完成)。 –