zoukankan      html  css  js  c++  java
  • 多线程和线程池

    有这样一个需求:你有一个list集合,需使用该list作为参数,调用另一个系统并返回结果后处理它(主要的目的是处理结果)
    解决方案:用线程池,不关闭线程池,将多个线程放入一个List集合中,使用invokeAll方法,相当于是将多个线程打包执行,统一返回,这样线程池可以一直不关闭,不用为了一个list开一个线程池,并且多个线程打包调用不会造成和其他用户的多线程冲突(究竟是你的线程还是我的线程):
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.invokeAll(List<new ExeRuleThread implement Callable<Objec>>);
    sample: https://blog.csdn.net/u014046563/article/details/89053115?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

    另一種解決思路:使用非返回結果的綫程,但傳入一個空的結果集合,在綫程中處理結果,例如:
    paramList//參數集合
    resultMap = new HashMap()//結果集合

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    for (int i = 0; i < paramList.size(); i++) {
    inputParam = paramList.get(i);
    cachedThreadPool.execute(new ExeRuleThread(inputParam......,resultMap) implements Runnable);
    }
    cachedThreadPool.shutdown();

    try {
    cachedThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
    logger.error("cachedThreadPool time out");
    }

  • 相关阅读:
    LeetCode 382. Linked List Random Node
    LeetCode 398. Random Pick Index
    LeetCode 1002. Find Common Characters
    LeetCode 498. Diagonal Traverse
    LeetCode 825. Friends Of Appropriate Ages
    LeetCode 824. Goat Latin
    LeetCode 896. Monotonic Array
    LeetCode 987. Vertical Order Traversal of a Binary Tree
    LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays
    LeetCode 636. Exclusive Time of Functions
  • 原文地址:https://www.cnblogs.com/javac/p/6964966.html
Copyright © 2011-2022 走看看