本文介绍了Java ExecutorService 实现辅助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..在下面的代码中,userList
获取大量数据,因为发送电子邮件需要很长时间.
In the following code, userList
gets high volume of data due to which sending email takes too long time.
如何加快应用程序的速度,以便更快地发送 50000 封电子邮件?也许使用 ExecutorService
?
How can I speed up the application such that 50000 emails are sent faster? Maybe with the use of an 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
}
}
推荐答案
尝试以这种方式并行化您的代码:
Try parallelize your code in such way:
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
必须是无状态的.
Also, note, if you don't want to have a headache - method sendMailTo
must be stateless.
这篇关于Java ExecutorService 实现辅助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论