Java多线程分批处理数据
生活随笔
收集整理的這篇文章主要介紹了
Java多线程分批处理数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景:發短信,當有數據量龐大的短信需要發送時,可以采用多線程的方式分批處理以提高效率,但線程要控制合適的數量,否則會極大消耗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;}@Overridepublic 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;}@Overridepublic 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;} }結果:
總結
以上是生活随笔為你收集整理的Java多线程分批处理数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聊聊CSS中的布局模式
- 下一篇: 四十三 毕设(下)我在软件园的那些日子里