如何在Java中并行处理对象列表

如何在Java中并行处理对象列表,java,multithreading,concurrency,multiprocessing,executorservice,Java,Multithreading,Concurrency,Multiprocessing,Executorservice,我在Java中有一个对象列表,就像列表中的千个对象一样,我正在迭代每个对象的列表并进行进一步处理。对每个对象进行相同的处理。这种顺序方法需要花费大量的处理时间,因此,我想用Java实现并行处理。我检查了Java中的executor框架,但陷入了困境 我认为有一种方法可以实现我的需求 我想实现一些固定数量的最小对象,每个线程将处理这些对象,这样每个线程都可以快速地完成工作并处理对象。我怎样才能做到这一点?或者,如果有任何其他方法可以实现我的要求,请分享 例如: 列表对象=新列表() 用于(对象:对

我在Java中有一个对象列表,就像列表中的千个对象一样,我正在迭代每个对象的列表并进行进一步处理。对每个对象进行相同的处理。这种顺序方法需要花费大量的处理时间,因此,我想用Java实现并行处理。我检查了Java中的executor框架,但陷入了困境

我认为有一种方法可以实现我的需求

我想实现一些固定数量的最小对象,每个线程将处理这些对象,这样每个线程都可以快速地完成工作并处理对象。我怎样才能做到这一点?或者,如果有任何其他方法可以实现我的要求,请分享

例如:

列表对象=新列表()

用于(对象:对象){ //为所有人做一些普通的操作 物体


}并行处理列表有许多选项:

使用并行流:

如果要使用线程数多于fork-join池的池,请使用executor服务提交任务:

ExecutorService es = Executors.newFixedThreadPool(10);
for(Object o: objects) {
    es.submit(() -> {
        //code here using Object o...
    }
}
前面的示例本质上与传统的executor服务相同,在不同的线程上运行任务

除此之外,您还可以使用completable future提交:

//You can also just run a for-each and manually add each
//feature to a list
List<CompletableFuture<Void>> futures = 
    objects.stream().map(object -> CompletableFuture.runAsync(() -> {
    //Your work on each object goes here, using object
})
//您也可以只为每个运行一个,然后手动添加每个
//将功能添加到列表中
上市期货=
objects.stream().map(对象->CompletableFuture.runAsync(()->{
//您在每个对象上的工作都在这里,使用对象
})

然后,如果需要,您可以使用
futures
对象检查每次执行的状态。

有许多并行处理列表的选项:

使用并行流:

如果要使用线程数多于fork-join池的池,请使用executor服务提交任务:

ExecutorService es = Executors.newFixedThreadPool(10);
for(Object o: objects) {
    es.submit(() -> {
        //code here using Object o...
    }
}
前面的示例本质上与传统的executor服务相同,在不同的线程上运行任务

除此之外,您还可以使用completable future提交:

//You can also just run a for-each and manually add each
//feature to a list
List<CompletableFuture<Void>> futures = 
    objects.stream().map(object -> CompletableFuture.runAsync(() -> {
    //Your work on each object goes here, using object
})
//您也可以只为每个运行一个,然后手动添加每个
//将功能添加到列表中
上市期货=
objects.stream().map(对象->CompletableFuture.runAsync(()->{
//您在每个对象上的工作都在这里,使用对象
})

然后,如果需要,您可以使用
futures
对象检查每次执行的状态。

您可以使用
ThreadPoolExecutor
,它将负责负载平衡。任务将分布在不同的线程上

以下是一个例子:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {

        // Fixed thread number
        ExecutorService service = Executors.newFixedThreadPool(10);

        // Or un fixed thread number
        // The number of threads will increase with tasks
        // ExecutorService service = Executors.newCachedThreadPool(10);

        List<Object> objects = new ArrayList<>();
        for (Object o : objects) {
            service.execute(new MyTask(o));
        }

        // shutdown
        // this will get blocked until all task finish
        service.shutdown();
        try {
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class MyTask implements Runnable {
        Object target;

        public MyTask(Object target) {
            this.target = target;
        }

        @Override
        public void run() {
            // business logic at here
        }
    }
}
import java.util.ArrayList;
导入java.util.List;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
公开课考试{
公共静态void main(字符串[]args){
//固定螺纹号
ExecutorService=Executors.newFixedThreadPool(10);
//或不固定的螺纹号
//线程的数量将随着任务的增加而增加
//ExecutorService=Executors.newCachedThreadPool(10);
列表对象=新的ArrayList();
用于(对象o:对象){
执行(newmytask(o));
}
//关闭
//这将被阻止,直到所有任务完成
service.shutdown();
试一试{
服务等待终止(Long.MAX_值,时间单位为毫秒);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
公共静态类MyTask实现Runnable{
目标对象;
公共MyTask(对象目标){
this.target=目标;
}
@凌驾
公开募捐{
//这里的业务逻辑
}
}
}

您可以使用
线程池执行器,它将负责负载平衡。任务将分布在不同的线程上

以下是一个例子:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {

        // Fixed thread number
        ExecutorService service = Executors.newFixedThreadPool(10);

        // Or un fixed thread number
        // The number of threads will increase with tasks
        // ExecutorService service = Executors.newCachedThreadPool(10);

        List<Object> objects = new ArrayList<>();
        for (Object o : objects) {
            service.execute(new MyTask(o));
        }

        // shutdown
        // this will get blocked until all task finish
        service.shutdown();
        try {
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class MyTask implements Runnable {
        Object target;

        public MyTask(Object target) {
            this.target = target;
        }

        @Override
        public void run() {
            // business logic at here
        }
    }
}
import java.util.ArrayList;
导入java.util.List;
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
公开课考试{
公共静态void main(字符串[]args){
//固定螺纹号
ExecutorService=Executors.newFixedThreadPool(10);
//或不固定的螺纹号
//线程的数量将随着任务的增加而增加
//ExecutorService=Executors.newCachedThreadPool(10);
列表对象=新的ArrayList();
用于(对象o:对象){
执行(newmytask(o));
}
//关闭
//这将被阻止,直到所有任务完成
service.shutdown();
试一试{
服务等待终止(Long.MAX_值,时间单位为毫秒);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
公共静态类MyTask实现Runnable{
目标对象;
公共MyTask(对象目标){
this.target=目标;
}
@凌驾
公开募捐{
//这里的业务逻辑
}
}
}
将列表拆分为多个子列表,并使用多线程处理 每个子列表都是平行的

公共类ParallelProcessListElements{
public void processList(int numberofthreads,ListtempList,
对象对象(obj,方法){
final int-sizeofList=templast.size();
final int sizeofpublist=sizeofList/numberofthreads;
List threadlist=new ArrayList();
对于(int i=0;i{
尝试{method.invoke(obj,subList);}catch(异常e){e.printStackTrace();}
});
线程列表。添加(th);
}
forEach(th->{th.start();try{Thread.sleep(10);}catch(异常e){});
}
}
公共类演示{
公共静态void main(字符串[]args){
List templast=new ArrayList();
/**
*广告