/** * 用户实例 */
public class User {
//用户姓名
private String name;
//用户id
private Integer id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User() {
}
public User(String name, Integer id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", id=" + id + '}';
}
}
public class BranchThread {
public static void main(String[] args) {
//准备数据源
List<User> userList = getInitUser();
// 定义每个线程处理多少用户
Integer count = 20;
//根据用户数确定需要多少个线程
List<List<User>> lists = splitList(userList, count);
//将用户传每个线程执行
for (List<User> list:lists) {
UserThread userThread=new UserThread(list);
Thread thread=new Thread(userThread);
//启动线程
thread.start();
}
}
/**初始话数据 * @return */
public static List<User> getInitUser() {
ArrayList<User> list = new ArrayList();
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setId(i);
String name = String.valueOf(i);
user.setName(name);
list.add(user);
}
return list;
}
/** 计算出需要多少个线程 * @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;
}
}
/** * 创建线程 * 给1000个人分批发送短信 */
public class UserThread implements Runnable{
private List<User> userList;
public UserThread(List<User> userList) {
this.userList = userList;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public void run() {
/* userList.forEach(user -> { System.out.println("线程"+Thread.currentThread().getId()+user.toString()); });*/
for (User user : userList) {
//实际项目中调用第三方发送短信的接口
System.out.println(new Date().getTime() +"线程"+Thread.currentThread().getId()+user.toString());
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10569.html