1
我的程序是一個無限循環。在進入循環之前,我實例化2 可調收件。它們分別執行需要並行運行的HTTP請求和返回結果。它們是不同的java類,它們不共享任何屬性/數據。然而,他們都更新了自己的內部屬性,某些需要在程序開始時保持活力的計數器,直到我停止。重用一個可調用的實例似乎工作。這雖然好嗎?
我的代碼看起來像這樣。請原諒我是否可怕,我已經6年沒有編碼了。
callable1 = new Callable1();
callable2 = new Callable2();
while(true) {
//Preparation of the dynamic parameters
...
callable1.setData(some_dynamic_parameters1);
callable2.setData(some_dynamic_parameters2);
ExecutorService threadPool = Executors.newFixedThreadPool(2);
CompletionService<String> completion = new ExecutorCompletionService<String>(threadPool);
completion.submit(callable1);
completion.submit(callable2);
threadPool.shutdown();
//I need to wait for both tasks to complete before going further
String firstReply = completion.take().get();
String secondReply = completion.take().get();
...
}
這兩個可調用的代碼看起來像這樣。它們的call()方法細節不同。
public class callable1 extends Callable {
private counters = new PositionCounters();
private data = null;
public void setData(data) {
this.data = data;
}
public String call() {
//Create HTTP query from information contained in [data]
...
//update internal counter.
counters.update(query_result)
}
}
每一次,我提交給可調用的執行者,在「櫃檯」,在每個被更新,似乎做的工作並行。但我不相信我的解決方案是最好的解決方案,因爲我讀過一個線程永遠不會被重用。然而,這就是我在這裏做的。我希望你對此有專家意見。你認爲實現這個目標的最好方法是什麼?
謝謝你的幫助!
可卡因的代碼是什麼? – 2014-08-29 11:23:07
創建'Callable1/2'是否真的需要很多時間才能重用它們? HTTP請求的時間會比這更長,所以這不完全是一個優化熱點。 – Kayaman 2014-08-29 11:24:05
我需要重用它們,因爲它們擁有我需要保持更新的計數器。如果我每次都創造新的,我會放棄這些櫃檯。 – 2014-08-29 11:26:45