Java实现多线程(excel处理)

时间:2014-04-03 23:12:52

标签: 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();
}
}

2 个答案:

答案 0 :(得分:0)

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

我建议您尝试使用ExeuctorService,并实施Runnable并发送Runnables以使其运行。当它可用时,它会自动将您发送的新Runnable分配给Thread

您可以通过调用ExecutorService来启动具有固定线程数的Executors.newFixedThreadPool(int numThreads)。然后拨打submit(Runnable runnableWithYourProcessing)。当你完成时不要忘记shutdown()

答案 1 :(得分:0)

我会这样做:

  • 定义一个实现Callable接口的Task类,并返回String
  • 任务类适用于具有给定索引的行。
  • 创建一个具有固定线程数的ExecutorService,并为Excel工作表中的每一行提交任务实例。
  • 收集Future<String>返回的Callable,并连接这些值以获得结果。