java多线程快速入门
Posted cppdy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程快速入门相关的知识,希望对你有一定的参考价值。
多线程应用实例(批量发送短信)
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; } }
以上是关于java多线程快速入门的主要内容,如果未能解决你的问题,请参考以下文章