在下面的代码中,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
}
}
尝试以这样的方式并行化代码:
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
必须是无状态的。
您可以使用ExecutorService
执行以下任务:
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
/* Add your logic here */
}
});
executorService.shutdown();
信息
- 你可以在这里找到它的java文档
- 这里提供了关于
ExecutorService
的更详细的教程