java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > JAVA处理for循环数据

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

作者:二拾三

这篇文章主要给大家介绍了关于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循环数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文