for循环使用多线程优化

package com.xrq;

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 main(String args[]) throws InterruptedException {
        Test test = new Test();
        long bt = System.currentTimeMillis();
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10;i++){
            list.add(i);
        }
        test.m1(list);
        long et2 = System.currentTimeMillis();
        System.out.println("[1]耗时:"+(et2 - bt)+ "ms");
        Thread thread = new Thread();
        long at = System.currentTimeMillis();
        test.m2();
        long et3 = System.currentTimeMillis();
        System.out.println("[2]耗时:"+(et3 - at)+ "ms");

    }

    public void m1( List<Integer> list) {
        ExecutorService pool = Executors.newCachedThreadPool();
        CountDownLatch latch = new CountDownLatch(list.size());
        for (int i = 0; i < list.size(); i++) {
            final int index = i;
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        new Thread().sleep(1000);
                        //模拟耗时操作
                        System.out.println("[1]" + Thread.currentThread().getName()+"----"+index);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        latch.countDown();
                    }
                }
            };
            pool.execute(run);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("[1] done!");
        pool.shutdown();
    }

    public void m2() {
        for (int i = 0; i < 10; i++) {
            try {
                new Thread().sleep(1000);  //模拟耗时操作
                System.out.println("[2]" + Thread.currentThread().getName()+"----"+i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("[2] done!");
    }
}

 

在 Java 中,可以使用多线程来加速执行 for 循环操作。我们可以将 for 循环任务分割成多个子任务,每个子任务由一个独立的线程执行,从而提高程序的并行度和执行效率。 以下是一个简单的示例代码,其中 for 循环被拆分成了 4 个子任务,每个子任务由一个独立的线程执行: ``` public class MultiThreadedForLoop { private static final int NUM_THREADS = 4; // 线程数 private static final int ARRAY_SIZE = 100000; // 数组大小 private static int[] array = new int[ARRAY_SIZE]; // 数组 public static void main(String[] args) throws InterruptedException { // 初始化数组 for (int i = 0; i < ARRAY_SIZE; i++) { array[i] = i; } // 创建线程池 ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); // 计算每个子任务的大小 int chunkSize = ARRAY_SIZE / NUM_THREADS; // 创建多个子任务,每个子任务由一个线程执行 List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < NUM_THREADS; i++) { int start = i * chunkSize; int end = (i == NUM_THREADS - 1) ? ARRAY_SIZE : (i + 1) * chunkSize; Future<Integer> future = executor.submit(new SumTask(start, end)); futures.add(future); } // 等待所有子任务执行完毕 int sum = 0; for (Future<Integer> future : futures) { sum += future.get(); } // 输出结果 System.out.println("Sum is " + sum); // 关闭线程池 executor.shutdown(); } // 子任务类,计算数组指定范围内的元素之和 private static class SumTask implements Callable<Integer> { private int start; private int end; public SumTask(int start, int end) { this.start = start; this.end = end; } @Override public Integer call() throws Exception { int sum = 0; for (int i = start; i < end; i++) { sum += array[i]; } return sum; } } } ``` 在上述代码中,我们使用了 Java 提供的 ExecutorService 来创建线程池,并将 for 循环任务拆分成多个子任务,每个子任务由一个 Callable 对象表示。我们可以通过调整线程数和子任务大小来优化程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大猩猩爱分享

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值