java多線程快速入門(六)
阿新 • • 發佈:2018-11-25
static code msg close play int vat one bsp
多線程應用實例(批量發送短信)
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; } publicUserEntityvoid 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();ListUtilsint 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; } }Send
java多線程快速入門(六)