且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java ExecutorService 实现辅助

更新时间:2023-12-03 13:45:46

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

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.