👉👉请优先查看大佬文章
| import java.util.ArrayList; |
| import java.util.List; |
| import java.util.concurrent.CountDownLatch; |
| import java.util.concurrent.ExecutorService; |
| import java.util.concurrent.Executors; |
| |
| public class test { |
| |
| |
| public static void exec(List<String> list) throws InterruptedException { |
| |
| int count = 300; |
| |
| int listSize = list.size(); |
| |
| int runSize = listSize%count > 0 ? ((listSize/count)+1) : (listSize/count); |
| |
| List<String> newlist = null; |
| |
| ExecutorService executor = Executors.newFixedThreadPool(runSize); |
| |
| CountDownLatch begin = new CountDownLatch(1); |
| CountDownLatch end = new CountDownLatch(runSize); |
| |
| for (int i = 0; i < runSize; i++) { |
| |
| if ((i + 1) == runSize) { |
| int startIndex = (i * count); |
| int endIndex = list.size(); |
| newlist = list.subList(startIndex, endIndex); |
| } else { |
| int startIndex = (i * count); |
| int endIndex = (i + 1) * count; |
| newlist = list.subList(startIndex, endIndex); |
| } |
| |
| MyThread mythead = new MyThread(newlist, begin, end); |
| |
| executor.execute(mythead); |
| } |
| |
| begin.countDown(); |
| end.await(); |
| |
| |
| executor.shutdown(); |
| } |
| |
| |
| |
| public static void main(String[] args) { |
| List<String> list = new ArrayList<String>(); |
| |
| for (int i = 0; i < 3000000; i++) { |
| list.add("hello" + i); |
| } |
| try { |
| exec(list); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| } |
| import java.util.List; |
| import java.util.concurrent.CountDownLatch; |
| |
| public class MyThread implements Runnable { |
| private List<String> list; |
| private CountDownLatch begin; |
| private CountDownLatch end; |
| |
| |
| public MyThread(List<String> list, CountDownLatch begin, CountDownLatch end) { |
| this.list = list; |
| this.begin = begin; |
| this.end = end; |
| } |
| |
| @Override |
| public void run() { |
| try { |
| for (int i = 0; i < list.size(); i++) { |
| |
| |
| |
| } |
| |
| |
| begin.await(); |
| } catch (InterruptedException e) { |
| |
| e.printStackTrace(); |
| } finally { |
| |
| |
| end.countDown(); |
| } |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步