我嘗試在返回成品線程的Java打印結果上製作多線程程序。 的事情是,當我運行這段代碼它只是卡住上第二個值是隊列:多線程程序中完成線程的實時輸出(CompletionService)
System.out.println("[!] Creaing pool");
int max_threads = 50;
ExecutorService threadPool = Executors.newFixedThreadPool(max_threads);
CompletionService<String> taskCompletionService =
new ExecutorCompletionService<String>(threadPool);
String url;
while(our_file.hasNext()){
url = our_file.next();
if (url.length()>0){
futures.add(
taskCompletionService.submit(
new GoGo(url)
)
);
}
int total_tasks = futures.size();
while(total_tasks>0){
for (int i=0; i<futures.size(); i++){
try{
Future result = taskCompletionService.poll();
if(result!=null && result.isDone()){
System.out.println(result.get());
total_tasks--;
}
}
catch (InterruptedException e) {
// Something went wrong with a task submitted
System.out.println("Error Interrupted exception");
e.printStackTrace();
} catch (ExecutionException e) {
// Something went wrong with the result
e.printStackTrace();
System.out.println("Error get() threw exception");
}
}
}
}
threadPool.shutdown();
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException e) {
}
...
class GoGo implements Callable{
private String url;
public GoGo(String received_url){
this.url = received_url;
}
public String call(){
String URL = this.url;
return url;
}
}
輸出是這樣的:
[!] Creaing pool
http://www.www1.com/
http://www.www2.ch/
,並在這一點上節目只是stucks。 我試圖移動循環迭代期貨數組出主循環提交線程,它工作正常,但萬一如果我會通過非常大的文件我需要實時輸出。 請幫我弄清楚瓶頸在哪裏,我無法找到使用CompletionService的非阻塞poll()方法的任何合適的代碼片段。 感謝您的任何答覆或參考。