需求:
假設有10萬個用戶,現在節假日做活動,需要給每個用戶發送一條活動短信,為了提高程序的效率,建議使用多線程分批發送.
這里值得注意的是:
每開一個線程都會占用CPU的資源,所以線程根據所需要的條數來決定就好,避免浪費,我們用的是一個小例子,只是說明了多線程處理提高了效率,實際的大規模場景中不建議使用,可選消息中間件來輪詢處理.
Demo示例:
這里為簡化展示,模擬示例10條內容,用分頁處理的方式來分批發送消息,每批為2條:
結構如下:
entity
|----------- UserEntity
batch
|----------- BatchSms
utils
|----------- ListUtils
相關類如下:
UserEntity:
package entity;
public class UserEntity {
private String userId;
private String userName;
public UserEntity(String userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "UserEntity{" +
"userId='" + userId + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
BatchSms:
package batch;
import entity.UserEntity;
import utils.ListUtils;
import java.util.ArrayList;
import java.util.List;
class UserSendThread implements Runnable {
private List<UserEntity> listUser;
public UserSendThread(List<UserEntity> listUser) {
this.listUser = listUser;
}
public void run() {
for (UserEntity userEntity : listUser) {
System.out.println(Thread.currentThread().getName() + " " + userEntity.toString());
}
}
}
public class BatchSms {
public static void main(String[] args) {
// 1. 初始化數據
List<UserEntity> list = initUser();
// 2.定義每個線程分批發送大小
int userCount = 2;
// 3.計算每個線程需要分批跑的數據
List<List<UserEntity>> splitList = ListUtils.splitList(initUser(), userCount);
for (int i = 0; i < splitList.size(); i++) {
List<UserEntity> list1 = splitList.get(i);
UserSendThread userSendThread = new UserSendThread(list1);
// 4.分批發送
Thread thread = new Thread(userSendThread, "線程" + i);
thread.start();
System.out.println();
}
}
private static List<UserEntity> initUser() {
List<UserEntity> list = new ArrayList<UserEntity>();
for (int i = 0; i < 10; i++) {
list.add(new UserEntity("userid:" + i, "username" + i));
}
return list;
}
}
ListUtils:
package utils;
import java.util.ArrayList;
import java.util.List;
public class ListUtils {
/**
*
* @methodDesc: 功能描述:(list 集合分批切割)
* @param: @param
* list
* @param: @param
* pageSize
* @param: @return
* @returnType:@param list 切割集合
* @returnType:@param pageSize 分頁長度
* @returnType:@return List<List<T>> 返回分頁數據
*/
static public<T> List<List<T>> splitList(List<T> list, int pageSize) {
int listSize = list.size();
int page = (listSize + (pageSize - 1)) / pageSize;
List<List<T>>listArray = new ArrayList<List<T>>();
for (int i = 0; i<page; i++) {
List<T>subList = new ArrayList<T>();
for (int j = 0; j<listSize; j++) {
int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;
if (pageIndex == (i + 1)) {
subList.add(list.get(j));
}
if ((j + 1) == ((j + 1) * pageSize)) {
break;
}
}
listArray.add(subList);
}
return listArray;
}
}
啟動后運行結果如下: