首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java实现多线程(excel处理)

Java实现多线程(excel处理)
EN

Stack Overflow用户
提问于 2014-04-03 23:12:51
回答 2查看 3K关注 0票数 1

因此,我的应用程序允许用户选择Microsoft文件,通常有300到5000行。有时甚至超过5000。我的问题是,在这个场景中使用多个线程会更有效吗?然后使用线程的最有效方法是什么。每个文件应该有自己的线程吗?此外,每个excel文件都是这样处理的:

代码语言:javascript
复制
  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

编辑代码

代码语言:javascript
复制
 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();
}
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-03 23:17:55

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

我的建议是您尝试使用ExecutorService,并实现Runnable并为其运行发送Runnable。当Thread可用时,它将自动将发送到的新Runnable分配给它。

只需调用ExecutorService,就可以使用固定数量的线程启动Executors.newFixedThreadPool(int numThreads)。那就打电话给submit(Runnable runnableWithYourProcessing)。当你完成的时候别忘了shutdown()

票数 2
EN

Stack Overflow用户

发布于 2014-04-03 23:19:54

我会这样做:

  • 定义一个实现Callable接口并返回String的任务类
  • 任务类将在具有给定索引的行上工作。
  • 创建一个具有固定线程数的ExecutorService,并为excel工作表中的每一行提交任务实例。
  • 收集由Future<String>返回的Callable,并将值连接起来以获得结果。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22850680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档