java线程池使用实例

以下是Java线程池使用的一个示例,多个list一次更新改为线程池每次批量更新,代码如下:

import model.User;
import org.springframework.util.CollectionUtils;
import util.SplitListUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author tian.jiyun
 * @date 2022/6/27 21:52
 */
public class ThreadM<T> {
    public void threadMethod(List<T> res, int subLength) {
        List<T> updateList = new ArrayList<>();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(20, 50, 4, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

        List<List<T>> splitList = SplitListUtils.splitList(res, subLength);
        //记录单个任务的执行次数
        CountDownLatch countDownLatch = new CountDownLatch(splitList.size());

        for (List<T> splist : splitList) {
            threadPoolExecutor.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < splist.size(); i++) {
                        // 将每一个对象进行数据封装, 并添加到一个用于存储更新数据的list
                        User user = (User) splist.get(i);
                        if (user != null) {
                            user.setAge(10 + i);
                            user.setId(100 + i);
                            user.setName("name" + i);
                            user.setBirthDay(LocalDateTime.now());
                        }
                    }
                }
            }));

            // 任务个数 - 1, 直至为0时唤醒await()
            countDownLatch.countDown();
        }

        try {
            // 让当前线程处于阻塞状态,直到锁存器计数为零
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new NullPointerException(e.getMessage());
        }
//        // 通过mybatis的批量插入的方式来进行数据的插入, 这一步还是要做判空
//        if (!CollectionUtils.isEmpty(updateList)) {
//            System.out.println("批量更新");
//        }
    }
}

 

posted @ 2022-06-27 22:34  明&天  阅读(4028)  评论(0编辑  收藏  举报