模拟多线程场景的使用--多线程分批处理数据

时间:2022-05-06 23:04:00

需求:目前某某商城有十万个用户,现在该商城需要做一个活动,于是需要给每一个用户发送一条该活动内容的短信。

 

1.创建用户实体类

/**
 * 用户实体类
 * @author Administrator
 *
 */
public class UserEntity {
	
	private String userId;
	private String userName;
	
	public UserEntity(String userId, String userName) {
		super();
		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 + "]";
	}
	
	
}

  2.

/**
 * 集合分批切割
 * @author Administrator
 *
 */
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>> 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;
	}
}

  3.

class UserSendThread implements Runnable{
	private List<UserEntity> listUser;
	//通过构造函数,传入每个线程需要执行的发送短信内容
	public UserSendThread(List<UserEntity> listUser){
		this.listUser=listUser;
	}
	
	@Override
	public void run() {
		for(UserEntity userEntity:listUser){
			System.out.println(Thread.currentThread().getName()+","+userEntity.toString());
		}
		System.out.println();
	}
	
}



public class BatchSms {

	public static void main(String[] args) {
		//1.初始化数据
		List<UserEntity> initUser=initUser();
		//2.定义每个线程分批发送大小
		int userCount=2;
		//3.计算每个线程需要分批跑的数据
		List<List<UserEntity>> splitList=ListUtils.splitList(initUser, userCount);
		for(int i=0;i<splitList.size();i++){
			List<UserEntity> list=splitList.get(i);
			UserSendThread userThread=new UserSendThread(list);
			//4.分配发送
			Thread thread=new Thread(userThread,"线程:"+i);
			thread.start();
		}
		
		

	}
	static private List<UserEntity> initUser(){
		List<UserEntity> list=new ArrayList<UserEntity>();
		for(int i=1;i<=11;i++){
			list.add(new UserEntity("userId:"+i,"userName:"+i));
		}
		return list;
	}

}

  模拟多线程场景的使用--多线程分批处理数据