多线程应用实例(批量发送短信)
1、创建实体类
package com.cppdy; public class UserEntity { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2、创建工具类
package com.cppdy; import java.util.ArrayList; import java.util.List; public class ListUtils { 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>> arrayList = 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; } } arrayList.add(subList); } return arrayList; } }
3、创建实例类
package com.cppdy; import java.util.ArrayList; import java.util.List; class sendMsgThread extends Thread{ List<UserEntity> userList; public sendMsgThread(List<UserEntity> list) { this.userList=list; } @Override public void run() { for (int i = 0; i < userList.size(); i++) { System.out.println("线程"+this.getId()+"发送短信给"+userList.get(i).getName()); } } } public class Send { public static void main(String[] args) { List<List<UserEntity>> splitList = ListUtils.splitList(initUser(), 40); for (int i = 0; i < splitList.size(); i++) { new sendMsgThread(splitList.get(i)).start(); } } public static List<UserEntity> initUser(){ ArrayList<UserEntity> userList = new ArrayList<>(); UserEntity userEntity; for (int i = 0; i < 150; i++) { userEntity = new UserEntity(); userEntity.setId(i); userEntity.setName("name"+i); userList.add(userEntity); } return userList; } }