1. 程式人生 > >java多執行緒快速入門(六)

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; } }
UserEntity

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; } }
ListUtils

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