1、源码
package email;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @ClassName sendEmail
* @Description TODO
* @Author Yubuer
* @Date 2022/6/9 10:32
* @Version 1.0
**/
public class SendEmail {
public static void main(String[] args) {
//创建线程池
BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque<>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS,blockingDeque);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
List<Email> list = new ArrayList<Email>();//接受邮件信息
list.add(new Email("1","1"));
list.add(new Email("2","2"));
list.add(new Email("3","3"));
Future<Boolean>[] futures = new Future[20];
int i = 0;
for(Email email : list){
Future<Boolean> res = threadPoolExecutor.submit(email);//开始执行线程
futures[i++] = res;
}
for (Future<Boolean> future: futures) {
try {
System.out.println(future.get(2,TimeUnit.SECONDS));//获取线程结果
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
}
class Email implements Callable<Boolean> {
String message;
String email;
public Email(String message, String email) {
this.message = message;
this.email = email;
}
@Override
public Boolean call() throws Exception {
Boolean res = send(message,email);//调用发送邮件的方法
return res;
}
private Boolean send(String message, String email) throws InterruptedException {
System.out.println(message+"发送成功");
System.out.println(email+"发送成功");
return true;
}
}
参考文章