当我们遇到成千上百万的信息要进行提交的时候该如何提高效率呢?
我用了线程池 直接来看代码
/**
* @author 一只迷茫在程序中的猫
* 创建线程池
* 核心线程池 数量为 100
* 线程池最大线程数 为 200
* 线程最多保持 60s 会终止 阻塞队列
* LinkedBlockingQueue
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
boolean isChina = false;
for (Integer reId : pushList) {
NtbUser user = ntbUserMapper.selectByPrimaryKey(reId);
try {
if (null == user.getCountryId() ||user.getCountryId()==SmsTaskServiceimpl.COUNTRY_ID_CHINA
|| StringUtils.isNullOrEmpty("" + user.getCountryId())) { // 中国地区
isChina = true;
}
// 内部类中用到成员变量都是常量
final String context = smsContent;
final boolean isChia = isChina;
// 把需要提交的东西交给线程
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
// logger.info("目前线程:" + Thread.currentThread().getName() + "正在执行任务" + user.getNickname());
SmsServiceImpl.this.sendSms(user.getTel(), context, isChia, "");
} catch (Exception e) {
logger.error("短信发送失败");
}
}
});
* 创建线程池
* 核心线程池 数量为 100
* 线程池最大线程数 为 200
* 线程最多保持 60s 会终止 阻塞队列
* LinkedBlockingQueue
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
boolean isChina = false;
for (Integer reId : pushList) {
NtbUser user = ntbUserMapper.selectByPrimaryKey(reId);
try {
if (null == user.getCountryId() ||user.getCountryId()==SmsTaskServiceimpl.COUNTRY_ID_CHINA
|| StringUtils.isNullOrEmpty("" + user.getCountryId())) { // 中国地区
isChina = true;
}
// 内部类中用到成员变量都是常量
final String context = smsContent;
final boolean isChia = isChina;
// 把需要提交的东西交给线程
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
// logger.info("目前线程:" + Thread.currentThread().getName() + "正在执行任务" + user.getNickname());
SmsServiceImpl.this.sendSms(user.getTel(), context, isChia, "");
} catch (Exception e) {
logger.error("短信发送失败");
}
}
});
代码中有两个知识点:
1.线程池
2.内部类
首先我在这里说明下我写这段代码的原因,有一个需求,要发给用户短信信息。这里的用户用户量大概是在1W左右。
如果我们直接用for循环去提交给短信商的话,效率会非常慢。所以这里我就开了个线程池。之前我只是知道有线程池这个东西。
但是从未有机会接触。今天刚好有机会接触,其实百度上很多很好的关于线程池的用法。这里我只提及怎么使用。
我们先创建一个线程池
/**
* @author sunny 创建线程池 核心线程池 数量为 100 线程池最大线程数 为 200 线程最多保持 60s 会终止 阻塞队列
* LinkedBlockingQueue
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
LinkedBlockingQueue是一个单向链表实现的阻塞队列,先进先出的顺序。支持多线程并发操作
具体了解 可以看 http://blog.csdn.net/dachengxi/article/details/52133024
然后进行让线程池工作的东西 进行提交。
内部类我之前也没有怎么接触。我还是个经验不足的小小菜鸟,证努力往前。
内部类中的成员变量必须是常量。在内部类要调用外部类的成员变量的时,可以定义一个常量的来接收成员变量
// 内部类中用到成员变量都是常量
final String context = smsContent;
final boolean isChia = isChina;
内部类要调用外部类的方法。可以使用外部类名.this.方法名。
这个是我用来记录每天用的小问题的。毕竟我还只是个小小喵。加油!!!!