Java教程:如何使用异步多线程处理业务并优雅关闭

正文:

版本一(CountDownLatch 计数器):

public void manyThread() {
    List<String> list = Arrays.asList("1", "2", "3");
    // 计数器
    CountDownLatch downLatch = new CountDownLatch(list.size());
    // 创建线程
    ExecutorService executorService = null;
    try {
        executorService = Executors.newFixedThreadPool(list.size());
        for (String item : list) {
            // 开启线程
            executorService.execute(() -> {
                try {
                    // 业务处理
                    System.out.println(item);
                } finally {
                    downLatch.countDown();
                }
            });
        }
        downLatch.await();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}

版本二(使用分布式锁多线程分段处理表数据并优雅关闭):

public class DataTest {

    /**
     * redis分布式锁
     */
    @Autowired
    private RedissonClient redissonClient;

    public static void main(String[] args) {
        // 获取分布式锁
        RLock lock = redissonClient.getLock("lock_key");
        if (lock.tryLock()) {
            // 获取锁成功,创建固定线程池
            ThreadPoolExecutor executorService = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(1000));

            try {
                Date minCreateTime = userMapper.selectMinCreateTime();
                if (minCreateTime == null) {
                    // 无数据
                    log.info("无数据");
                    return;
                }
                Date maxCreateTime = userMapper.selectMaxCreateTime();

                Date startCreateTime = minCreateTime;
                Date endCreateTime = null;
                do {
                    // 时间递增24小时
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(minCreateTime);
                    calendar.add(Calendar.HOUR, 24);
                    endCreateTime = calendar.getTime();
                    if (endCreateTime.getTime() >= maxCreateTime.getTime()) {
                        // 时间超出
                        endCreateTime = maxCreateTime;
                    }

                    List<User> users = userMapper.selectAllByCreateTime(startCreateTime, endCreateTime);
                    if (!CollectionUtils.isEmpty(users)) {
                        // 使用队列分割list
                        List<List<User>> partition = Lists.partition(users, 1000);
                        partition.forEach(user -> {
                            // 创建带有返回值集合
                            List<Future<String>> futures = new ArrayList<>();
                            user.forEach(item -> {
                                // 子线程
                                Callable<String> callable = processing();
                                futures.add(executorService.submit(callable));
                            });
                            try {
                                // 获取所有并发任务的运行结果
                                for (Future<String> f : futures) {
                                    // 从Future对象上获取任务的返回值,并输出到控制台
                                    log.debug("子线程执行完成,订单号:{}", f.get());
                                }
                            } catch (Exception e) {
                                log.error("子线程执行异常,原因:{}", e.toString());
                            }
                        });
                    }
                    startCreateTime = endCreateTime;
                } while (endCreateTime.getTime() != maxCreateTime.getTime());
            } catch (Exception e) {
                log.error("异常:{}", e.toString());
            } finally {
                if (!executorService.isShutdown()) {
                    executorService.shutdown();
                }
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        }
    }

    /**
     * 业务处理
     */
    public Callable<String> processing() {
        Callable<String> callable = () -> {
            // 业务处理
            return "成功";
        };
        return callable;
    }
}

你可能感兴趣的:(java,大数据,开发语言)