JAVA多线程处理for循环数据详细讲解

 更新时间:2023年07月28日 11:35:59   作者:二拾三  
这篇文章主要给大家介绍了关于JAVA多线程处理for循环数据的相关资料,我们在代码中经常需要使用for循环这个操作来达到目的,而当for循环的次数过多时我们会发现执行效率会变的很低,整体耗时非常多,需要的朋友可以参考下

1.对for循环内数据启用多线程执行,主线程与子线程无先后顺序

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            ThreadUtil.execAsync(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + "执行完");
            });
            System.out.println("第" + i + "个线程");
        }
        System.out.println("完成");
    }

执行结果:

2.对for循环内数据启用多线程执行,主线程在所有子线程执行完成之后执行

    public static void main(String[] args) throws InterruptedException {
        //初始化线程数量
        CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            ThreadUtil.execute(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + "执行完");
                //调用线程计数器-1
                countDownLatch.countDown();
            });
            System.out.println("第" + i + "个线程");
        }
        //唤醒主线程
        countDownLatch.await();
        System.out.println("完成");
    }

执行结果:

3.对for循环内数据启用多线程执行,主线程在所有子线程执行完成之后执行

 public static void main(String[] args) throws InterruptedException {
        // 线程个数
        int N = 10;
        // 实例化一个倒计数器,N指定计数个数
        CountDownLatch countDownLatch = new CountDownLatch(N);
        for (int i = 0; i < N; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                        System.out.println("子线程" + Thread.currentThread().getName() + "休眠结束");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    	// 计数减一
                        countDownLatch.countDown(); 
                    }
                }
            }).start();
        }
        // 阻塞,等待当计数减到0时,执行后面的代码
        countDownLatch.await();
        System.out.println("结束");
    }

执行结果:

4. JAVA多线程10个线程处理1000个数据

    public static void main(String[] args) throws Exception {
        List<Integer> idList = new ArrayList<>();
        for (int i = 1; i <= 1000; i++) {
            idList.add(i);
        }
        int threadNum = 10;
        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        CountDownLatch countDownLatch = new CountDownLatch(threadNum);
        int perSize = idList.size() / threadNum;
        // 定义接受数据集合  多线程情况下,使用线程安全集合
        List<Integer> resultList = Collections.synchronizedList(new ArrayList());
        for (int i = 0; i < threadNum; i++) {
            MultiThread thread = new MultiThread();
            thread.setIdList(idList.subList(i * perSize, (i + 1) * perSize));
            thread.setCountDownLatch(countDownLatch);
            thread.setResultList(resultList);
            executorService.submit(thread);
        }
        countDownLatch.await();
        executorService.shutdown();
        // 查看结果
        System.out.println(resultList.size());
        System.out.println(resultList.stream().sorted().collect(Collectors.toList()));
    }
}
class MultiThread extends Thread {
    private List<Integer> idList;
    private CountDownLatch countDownLatch;
    private List<Integer> result;
    public void setResultList(List<Integer> result) {
        this.result = result;
    }
    public void setIdList(List<Integer> idList) {
        this.idList = idList;
    }
    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        try {
            // 数据处理
            for (Integer integer : idList) {
                if (integer % 2 == 0) {
                    result.add(integer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countDownLatch != null) {
                countDownLatch.countDown();
            }
        }
    }

执行结果:

总结

到此这篇关于JAVA多线程处理for循环数据的文章就介绍到这了,更多相关JAVA处理for循环数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot整合Javamail实现邮件发送的详细过程

    SpringBoot整合Javamail实现邮件发送的详细过程

    日常开发过程中,我们经常需要使用到邮件发送任务,比方说验证码的发送、日常信息的通知等,下面这篇文章主要给大家介绍了关于SpringBoot整合Javamail实现邮件发送的详细过程,需要的朋友可以参考下
    2022-10-10
  • Java 如何判断Integer类型的值是否相等

    Java 如何判断Integer类型的值是否相等

    这篇文章主要介绍了Java 如何判断Integer类型的值是否相等操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • Spring Boot整合MyBatis连接Oracle数据库的步骤全纪录

    Spring Boot整合MyBatis连接Oracle数据库的步骤全纪录

    这篇文章主要给大家介绍了关于Spring Boot整合MyBatis连接Oracle数据库的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • spring-boot-maven-plugin引入出现爆红(已解决)

    spring-boot-maven-plugin引入出现爆红(已解决)

    这篇文章主要介绍了spring-boot-maven-plugin引入出现爆红(已解决),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Spring Boot读取配置属性常用方法解析

    Spring Boot读取配置属性常用方法解析

    这篇文章主要介绍了Spring Boot读取配置属性常用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • spring boot如何使用AOP统一处理web请求

    spring boot如何使用AOP统一处理web请求

    这篇文章主要介绍了spring boot如何使用AOP统一处理web请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Springmvc基于fastjson实现导包及配置文件

    Springmvc基于fastjson实现导包及配置文件

    这篇文章主要介绍了Springmvc基于fastjson实现导包及配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 使用多种方式实现遍历HashMap的方法

    使用多种方式实现遍历HashMap的方法

    下面小编就为大家带来一篇使用多种方式实现遍历HashMap的方法。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-05-05
  • SpringBoot事件发布和监听详解

    SpringBoot事件发布和监听详解

    今天去官网查看spring boot资料时,在特性中看见了系统的事件及监听章节,所以下面这篇文章主要给大家介绍了关于SpringBoot事件发布和监听的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2021-11-11
  • 使用Spring Boot AOP处理方法的入参和返回值

    使用Spring Boot AOP处理方法的入参和返回值

    这篇文章主要介绍了使用Spring Boot AOP处理方法的入参和返回值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08

最新评论