シナリオ: SMSを送信する送信するデータが大量にある場合は、マルチスレッドバッチ処理を使用して効率を向上させることができますが、スレッド数を適切に制御する必要があります。そうしないと、CPUリソースが大幅に消費されます。
上記のコード:
ページングクラスPageUtilを作成します
/**
* 分页
* @param list 切割数据集合
* @param pageSize 每页记录数
* @param <T>
* @return
*/
public static <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;
}
Runnableインターフェイスを実装するスレッドクラスTestThreadを作成します
public class TestThread implements Runnable{
private List<UserEntity> userEntityList;
public TestThread(List<UserEntity> userEntityList) {
this.userEntityList = userEntityList;
}
@Override
public void run() {
for (UserEntity userEntity: userEntityList){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
System.out.println("name:"+Thread.currentThread().getName()+userEntity.toString());
}
}
}
エンティティクラスUserEntityを作成します
public class UserEntity {
private String userId;
private String userName;
public UserEntity() {
}
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 + '\'' +
'}';
}
}
メインクラスBatchThreadを作成します
public class BatchThread {
public static void main(String[] args) {
List<UserEntity> userList = initUser();
int userCount = 2;
List<List<UserEntity>> pageList = PageUtil.splitList(userList, userCount);
for (int i = 0; i < pageList.size(); i++){
List<UserEntity> userEntityList = pageList.get(i);
TestThread testThread = new TestThread(userEntityList);
Thread thread = new Thread(testThread);
thread.start();
}
}
public static List<UserEntity> initUser(){
List<UserEntity> userEntityList = new ArrayList<>();
for (int i = 1; i <= 11; i++){
userEntityList.add(new UserEntity("id:"+i, "username:"+i));
}
return userEntityList;
}
}
結果: