首页 > 编程语言 >Java 多线程处理 for 循环数据

Java 多线程处理 for 循环数据

时间:2023-08-23 11:33:57浏览次数:48  
标签:Java void System 循环 线程 countDownLatch println 多线程 out

对于必须在for循环内进行查询的场景,可采用以下几种方式进行优化。

1、主线程与子线程无先后顺序

    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、主线程在所有子线程执行完成之后执行

    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、主线程在所有子线程执行完成之后执行

 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、示例Demo

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,void,System,循环,线程,countDownLatch,println,多线程,out
From: https://www.cnblogs.com/995i996/p/17650755.html

相关文章

  • Java 魔法类Unsafe详解
    Java魔法类Unsafe详解本文整理完善自下面这两篇优秀的文章:Java魔法类:Unsafe应用解析-美团技术团队-2019openinnewwindowJava双刃剑之Unsafe类详解-码农参上-2021​ 阅读过JUC源码(JUC就是Java.util.concurrent包,他是一个处理线程的工具包,从jdk1.5之后开......
  • Java 常见并发容器总结
    Java常见并发容器总结​ JDK提供的这些容器大部分在java.util.concurrent包中。ConcurrentHashMap:线程安全的HashMapCopyOnWriteArrayList:线程安全的List,在读多写少的场合性能非常好,远远好于Vector。ConcurrentLinkedQueue:高效的并发队列,使用链表实现。可以......
  • 20230622 java.io.FileOutputStream
    介绍java.io.FileOutputStreampublicclassFileOutputStreamextendsOutputStream提供附着在一个磁盘文件上的输出流API构造器FileOutputStream(Stringname)throwsFileNotFoundExceptionFileOutputStream(Stringname,booleanappend)FileOutputStream(Filefile......
  • 20230622 java.io.DataOutputStream
    介绍java.io.DataOutputStreampublicclassDataOutputStreamextendsFilterOutputStreamimplementsDataOutput支持写出基本数据类型API构造器DataOutputStream(OutputStreamout)publicsize返回目前为止写入的字节数......
  • 20230622 java.io.DataOutput
    介绍java.io.DataOutputpublicinterfaceDataOutput定义了用于以二进制格式写数组、字符、boolean值和字符串的方法API写字节writevoidwrite(intb)throwsIOException;voidwrite(byteb[])throwsIOException;voidwrite(byteb[],intoff,intlen)throws......
  • 20230622 java.io.DataInputStream
    介绍java.io.DataInputStreampublicclassDataInputStreamextendsFilterInputStreamimplementsDataInput支持读取基本数据类型API构造器DataInputStream(InputStreamin)......
  • 20230622 java.io.DataInput
    介绍java.io.DataInputpublicinterfaceDataInputAPI读取字节readFullyvoidreadFully(byteb[])throwsIOException;voidreadFully(byteb[],intoff,intlen)throwsIOException;从输入流读取并存储到缓冲器数组boff:偏移量,从b[off]开始使用数组len:......
  • 20230622 java.io.BufferedOutputStream
    介绍java.io.BufferedOutputStreampublicclassBufferedOutputStreamextendsFilterOutputStreamwrite方法写入的字节先存入内部的bytebuf[],填满后再写入文件API构造器BufferedOutputStream(OutputStreamout)BufferedOutputStream(OutputStreamout,intsize)......
  • 20230622 java.io.BufferedInputStream
    介绍java.io.BufferedInputStreampublicclassBufferedInputStreamextendsFilterInputStreamread方法读取字节时,先读取内部的缓冲区bytebuf[],当缓冲区读完后,从底层输入流再读入数据填充缓冲区API构造器BufferedInputStream(InputStreamin)BufferedInputStream(I......
  • 20230621 java.io.Writer
    介绍java.io.WriterpublicabstractclassWriterimplementsAppendable,Closeable,FlushableAPIwriteabstractvoidwrite(charcbuf[],intoff,intlen)throwsIOException;唯一的抽象方法voidwrite(intc)throwsIOException写入一个字符(两个字节,一个......