使用多线程的Executor框架来处理数据

时间:2017-11-02 18:25:31

标签: java

我正在开发一个应用程序,我必须从数据库中检索大量数据并将其写入文件。为此,我计划使用Executor框架来提高应用程序的性能。我有两个列表,我的代码如下。

for(String n:studentNameList){
    for(String s:studentClassList){
        // here I will call a method which will take result set object and will write data to the file
    }
}

这两个列表都包含大量数据。对于名称的每个组合 和类它将在输出目录中创建一个文件。没有多线程代码工作正常但是为了提高性能我读了一些文章并且知道我可以使用执行器框架来提高性能。我之前没有使用它,而且我对多线程没有很好的掌握。我正在使用执行程序框架进行如下操作:

ExecutorService service = Executors.newFixedThreadPool(10);

for(String n:studentNameList){
    service.submit(n);
    for(String s:studentClassList){
        service.submit(s);
        // here I will call a method which will take result set object and will write data to the file
    }
}
service.shutdown();

我做得对吗?这是我处理更多记录的正确方法。请建议。请告诉我错误的地方以及如果需要我如何纠正。

1 个答案:

答案 0 :(得分:0)

你的核心逻辑是 void getAndSaveData(String name, String class) { ... }

单线程执行代码是:

for ( String name : students ) {
    for ( String clazz : classes ) {
       getAndSaveData(name, clazz);
    }
}

要将其转换为多线程模式,请将对方法的调用转换为:

ExecutorService executors = Executors.newFixedThreadPool(10);

for ( String name : students ) {
    for ( String clazz : classes ) {
       Runnable r = () -> getAndSaveData(name, clazz);
       executors.submit(r);
    }
}

executors.shutdown(); // marks that no new tasks will come
// wait for 5 minutes before proceeding
boolean allDone = executors.awaitTermination(5, TimeUnit.MINUTES);
// allDone will have status have everything completed in 5 minutes or not

更多详情可在https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

中找到