0

在以下代码中,userList由于发送电子邮件花费的时间过长,因此获取了大量数据。

如何加快应用程序的速度,以便更快地发送 50000 封电子邮件?也许使用ExecutorService?

List<String[]> userList = new ArrayList<String[]>();
void getRecords() {
    String [] props=null;
    while (rs.next()) {
    props = new String[2];
    props[0] = rs.getString("useremail");
    props[1] = rs.getString("active");
    userList.add(props);
    if (userList.size()>0) sendEmail();   
}
void sendEmail() {
    String [] user=null;
    for (int k=0; k<userList.size(); k++) { 
        user = userList.get(k);
        userEmail = user[0];         
        //send email code
    }
}
4

2 回答 2

3

尝试以这种方式并行化您的代码:

private final int THREADS_NUM = 20;

void sendEmail() throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool( THREADS_NUM );
    for ( String[] user : userList ) { 
        final String userEmail = user[0];         
        executor.submit( new Runnable() {
            @Override
            public void run() {
                sendMailTo( userEmail );
            }
        } );
    }
    long timeout = ...
    TimeUnit timeunit = ...
    executor.shutdown();
    executor.awaitTermination( timeout, timeunit );
}

void sendMailTo( String userEmail ) {
// code for sending e-mail
}

另外,请注意,如果您不想头疼 - 方法sendMailTo必须是无状态的。

于 2012-09-06T14:29:41.583 回答
0

ExecutorService您可以使用如下方式执行此类任务:

ExecutorService executorService = Executors.newSingleThreadExecutor();

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");
        /* Add your logic here */
    }
});

executorService.shutdown();

信息

于 2012-09-06T14:21:51.600 回答