Java实现多线程(excel处理)

标签 java excel apache-poi

因此,我的应用程序允许用户选择 Microsoft Excel 文件,通常有 300 到 5000 行。有时甚至超过 5000。我的问题是在这种情况下使用多个线程是否会更有效,以及利用线程的最有效方法是什么。每个文件应该有自己的线程还是什么?这也是每个 Excel 文件的处理方式:

  Load file
  loop until eof
   iterate through rows and cells
   Assign each cell to variable x  
   concatenate required chars to begin and end of x
   Append x to y
  End loop

  Write y to text file

编辑代码

 public class FileParse implements Callable<String>
 {

private String fPath;
private BufferedReader br;
private String line;

@Override
public String call()
{
line = "";
try{
        br = new BufferedReader(new FileReader(fPath));

        String sCurrentLine = "";

        while ((sCurrentLine = br.readLine()) != null) {
            line += sCurrentLine;

        }
    }catch(IOException exc){
        System.out.println("Cant load file");

    }


return line;
}


public FileParse (String location)
{
    br = null;
    fPath = location;

}


public static void main(String[] args)
{
    ExecutorService executor = Executors.newFixedThreadPool(10);

    Callable<String> t1 = new FileParse("rsrc\\data12.txt");
    Callable<String> t2 = new FileParse("rsrc\\data13.txt");    

    Future<String> fut1 = executor.submit(t1);
    Future<String> fut2 = executor.submit(t2);


    try{

    System.out.println(fut1.get());
    System.out.println(fut2.get());
    }catch(InterruptedException | ExecutionException e){

    }
    executor.shutdown();
}
}

最佳答案

使用多线程会更快,是的。每个文件一个线程听起来不错,但您仍然需要某种限制(太多线程会带来很多问题)。

我建议你尝试一下ExecutorService ,并实现Runnable并发送 Runnables 让它运行。当线程可用时,它会自动将您发送的新 Runnable 分配给该线程。

您只需调用 Executors.newFixedThreadPool(int numThreads) 即可启动具有固定数量线程的 ExecutorService。然后只需调用submit(Runnable runnableWithYourProcessing)。完成后不要忘记shutdown()!

关于Java实现多线程(excel处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850680/

相关文章:

java - 如何在 Java 中使用 openxml 在 Excel 中创建超链接

java - Spring Autowire - 需要接口(interface)和实现 DAO 类吗?

java - 触发 REST 调用时无法解释某些汉字

java - 如何使用更改监听器 JavaFX 在两个 ListView 之间移动项目

每个 PDF 的 VBA 嵌套

arrays - 索引匹配不同日期和值之间的搜索

excel - 我想比较 Excel 中不同工作表中的两个列表以查找任何重复项

java - remove() 函数不删除 excel 中的任何行

java - 如何在java中将二维数组的子数组引用为一维数组

java - 打开使用 POI API 创建的文件时 Excel 被损坏