我尝试在返回完成线程的 Java 打印结果上制作多线程程序。问题是,当我运行此代码时,它只会卡在队列中的第二个值上:
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/
而此时程序只是卡住了。我试图将迭代期货数组的循环移出提交线程的主循环,它工作得很好,但如果我要通过非常大的文件,我需要实时输出。请帮我找出瓶颈在哪里,我找不到任何合适的代码,使用来自 CompletionService 的非阻塞 poll() 方法。感谢您的任何回答或参考。