我正在用JSoup编写简单的html解析器。我有大约5万个链接要检查,所以我认为这是学习紧密线程和同时学习的好机会。我在ExecutorService中注册了8个任务:其中6个解析了存储在ArrayLists中的一些数据的链接,然后将其添加到BlockingQueues。其中两个任务是基于BufferedWriter的文件编写器。问题是当我的6个任务完成所有链接时,文件编写器停止从BlockingQueue写入数据,所以我丢失了部分数据。我是java中的新手,所以如果你能帮我一把......代码:
主档案:
public static void main(String[] args) {
BlockingQueue<ArrayList<String>> units = new ArrayBlockingQueue<ArrayList<String>>(50, true);
BlockingQueue<ArrayList<String>> subjects = new ArrayBlockingQueue<ArrayList<String>>(50, true);
File subjectFile = new File("lekarze.csv");
File unitFile = new File("miejsca.csv");
ExecutorService executor = Executors.newFixedThreadPool(9);
executor.submit(new Thread(new FileSaver(subjects, subjectFile)));
executor.submit(new Thread(new FileSaver(units, unitFile)));
for(int i = 29323; i < 29400; i++){
executor.submit(new ParserDocsThread(i, subjects, units, errors));
}
executor.shutdown();
}
FileSaver类:
package parser;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
public class FileSaver implements Runnable {
private BlockingQueue<ArrayList<String>> toWrite = null;
private File outputFile = null;
private BufferedWriter writer = null;
public FileSaver(BlockingQueue<ArrayList<String>> queue, File file){
toWrite = queue;
outputFile = file;
}
public void run() {
try {
writer = new BufferedWriter(new FileWriter(outputFile, true));
while(true){
try{
save(toWrite.take());
} catch(InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void save(ArrayList<String> data){
String temp ="";
int size = data.size();
for(int i = 0; i < size; i++){
temp += data.get(i);
if(i != size - 1) temp += '\t';
}
try {
writer.write(temp);
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在ParserDocsThread中,我只使用put()方法向BlockingQueue添加元素。
答案 0 :(得分:0)
您的消费者线程不会干净地结束,因为take()
调用正在等待新数组,并且没有关闭缓冲的编写器。 ServiceExecutor放弃等待这些线程完成并杀死它们。这导致写入器中的最后一行未写入磁盘。
您应该使用poll(10, TimeUnit.SECONDS)
(但具有适当的超时)。超时后,您的消费者将放弃生产者,您应该确保正确关闭缓冲的编写器,以便正确打印出最后一个缓冲区。
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, true)))
{
while(true){
List<String> data = toWrite.poll(10, TimeUnit.SECONDS);
if (data == null) {
break;
}
save(data, writer);
}
} catch (...) {
}
我把缓冲的编写器放在try-with-resources中(所以这里的try会自动关闭编写器)并将它传递给你的save方法,但是你可以按照自己的方式执行,并手动关闭writer在你想要的最后一个块中:
try {
...
} catch(...) {
} finally {
writer.close(); // Closes and flushes out the remaining lines
}
您可能还希望在执行程序服务器上调用awaitTermination
(如此:How to wait for all threads to finish, using ExecutorService?),等待时间大于轮询超时。