繁体   English   中英

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

[英]Using Executor framework of multi threading to process data

我正在开发一个应用程序,在该应用程序中,我必须从数据库中检索大量数据并将其写入文件。 为此,我计划使用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
    }
}

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

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();

我做对了吗? 是我可以处理更多记录的正确方法。请提出建议。 请告诉我哪里错了,以及在需要时如何纠正。

您的核心逻辑是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中找到更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM