java for循环内执行多线程 您所在的位置:网站首页 pythonforin循环多数据 java for循环内执行多线程

java for循环内执行多线程

2023-06-15 07:31| 来源: 网络整理| 查看: 265

目录

一、java用多线程来加快循环效率(推荐第3种!!!!)

 第一种:线程池搭配闭锁

 第二种:分页概念执行线程

 第三种:分页概念执行线程进阶版!!!!

一、java用多线程来加快循环效率(推荐第3种!!!!)  第一种:线程池搭配闭锁

涉及知识:Executors(线程池)、CountDownLatch(闭锁)

优点:代码简洁,方便阅读,性能稳定;

缺点:Executors创建的线程池是公用的,如果多个地方使用这种循环多线程的方式,就会抢夺线程池资源,这样运行速度也会降低;

import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class test{ public static void main(String[] args) throws Exception { /** * 两个要点: * 1.用Executors实现固定大小的线程池,从而达到控制硬件资源消耗的目的。 * 2.用CountDownLatch(闭锁),来确保循环内的多线程都执行完成后,再执行后续代码 */ // 固定的线程池(当前线程池大小为5 final ExecutorService executor = Executors.newFixedThreadPool(5); // 初始化数据 List list = new ArrayList(); for(int i=0;i= end) break; new Thread(new Runnable() { @Override public void run() { for (int j = beign; j < end; j++) { try{ function.run(j); }catch (Exception e){ e.printStackTrace(); } // 闭锁-1 cdl.countDown(); } } }).start(); } int time = this.timeOut != null ? this.timeOut : 60; // 调用闭锁的await()方法,该线程会被挂起,它会等待直到count值为0才继续执行 // 这样我们就能确保上面多线程都执行完了才走后续代码 try{ if(!cdl.await(time, TimeUnit.MINUTES)){ throw new TheadMultisException("Executed for more than "+ time +" minutes"); } }catch (InterruptedException e){ throw e; } } public class TheadMultisException extends Exception{ public TheadMultisException() { super(); } public TheadMultisException(String s) { super(s); } } public static void main(String[] args) throws Exception { // 初始化数据 final List list = new ArrayList(); for(int i=0;i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有