JAVA定义一个线程池,循环遍历list

版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/chenyao1994 https://blog.csdn.net/chenyao1994/article/details/84174156

前言

如果list有1000条数据,你瞬间就起了一千个线程,而且需要人为写代码注意同步问题。你这个代码最严重的问题是,子线程处理结果你主线程要拿到很麻烦,这一点在真正项目应用中很重要!

思路

  1. 把你“遍历一次需要15秒左右”这个事情写到一个类里面,类实现Callable接口,这个我们称之为一个任务
  2. 然后你不是有个List吗,遍历这个list,构建一个任务数组
  3. 创建ConcurrentExcutor对象并执行数组里面的任务

下面是我自己项目中的调用代码,供你参考(ProcessNumTask就是那个实现Callable的任务):

ProcessNumTask[] tasks = new ProcessNumTask[tempList.size()];
        for(int i=0; i<tempList.size(); i++)
        {
            tasks[i] = new ProcessNumTask(tempList.get(i));
        }
        ConcurrentExcutor<ReportProcessInfo> ce = new ConcurrentExcutor<ReportProcessInfo>(tasks, 5, result);
        ce.excute();

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
 * 并发处理器
 * 适用于如下场景(举例):
 * 一个任务队列, 有150个任务需要并发处理,使用此对象,可以每次并发执行20次(可设置),则总共串行执行8次并发,可获取执行结果
 *
 * @param <T> 类型T限制为任务Callable使用的数据对象和返回结果的数据对象为同一个bean
 */
public class ConcurrentExcutor<T>
{
    /** 非空,所有任务数组 */
    private Callable<T>[] tasks;
    /** 非空,每次并发需要处理的任务数 */
    private int numb;
    /** 可选,存放返回结果,这里有个限制,泛型T必须为Callable返回的类型T */
    private List<T> result;
     
    /**
     * 无参构造
     */
    public ConcurrentExcutor()
    {
        super();
    }
    /**
     * 不需要返回结果的任务用此创建对象
     * @param tasks
     * @param numb
     */
    public ConcurrentExcutor(Callable<T>[] tasks, int numb)
    {
        super();
        this.tasks = tasks;
        this.numb = numb;
    }
    /**
     * 需要结果集用此方法创建对象
     * @param tasks
     * @param numb
     * @param result
     */
    public ConcurrentExcutor(Callable<T>[] tasks, int numb, List<T> result)
    {
        super();
        this.tasks = tasks;
        this.numb = numb;
        this.result = result;
    }
    public void excute()
    {
        // 参数校验
        if(tasks == null || numb < 1)
        {
            return;
        }
         
        // 待处理的任务数
        int num = tasks.length;
        if(num == 0){
            return;
        }
        // 第一层循环,每numb条数据作为一次并发
        for(int i=0; i<(int)Math.floor(num/numb) + 1; i++)
        {
            // 用于记录此次numb条任务的处理结果
            Future[] futureArray;
            if(numb > num)
            {
                futureArray = new Future[num];
            }
            else
            {
                futureArray = new Future[numb];
            }
            // 创建线程容器
            ExecutorService es = Executors.newCachedThreadPool();
            // 第二层循环,针对这numb条数据进行处理
            for(int j=i*numb; j<(i+1)*numb; j++)
            {
                // 如果超出数组长度,退出循环
                if(j + 1 > num)
                {
                    break;
                }
                // 执行任务,并设置Future到数组中
                futureArray[j%numb] = es.submit(tasks[j]);
            }
            // 将结果放入result中
            if (result != null)
            {
                for (int j = 0; j < futureArray.length; j++)
                {
                    try
                    {
                        if(futureArray[j] != null)
                        {
                            Object o = futureArray[j].get();
                            result.add((T)o);
                        }
                    }
                    catch (InterruptedException e)
                    {
                        System.out.println("处理Future时发生InterruptedException异常,目标Future为: " + futureArray[j].toString());
                        e.printStackTrace();
                    }
                    catch (ExecutionException e)
                    {
                        System.out.println("处理Future时发生ExecutionException异常,目标Future为: " + futureArray[j].toString());
                        e.printStackTrace();
                    }
                }
            }
            es.shutdown();
        }
    }

import java.util.ArrayList;  
import java.util.List;  
import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.Future;  
public class Test {  
    public static void main(String[] args) {  
        try {  
            List<String> list = new ArrayList<>();  
            for (int i = 0; i < 100; i++) {  
                list.add(i + ",");  
            }   
            System.out.println(new Test().list2Str(list, 5));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    public String list2Str(List<String> list, final int nThreads) throws Exception {  
        if (list == null || list.isEmpty()) {  
            return null;  
        }  
        StringBuffer ret = new StringBuffer();  
        int size = list.size();  
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);  
        List<Future<String>> futures = new ArrayList<Future<String>>(nThreads);  
          
        for (int i = 0; i < nThreads; i++) {  
            final List<String> subList = list.subList(size / nThreads * i, size / nThreads * (i + 1));  
            Callable<String> task = new Callable<String>() {  
                @Override  
                public String call() throws Exception {  
                    StringBuffer sb = new StringBuffer();  
                    for (String str : subList) {  
                        sb.append(str);  
                    }  
                    return sb.toString();  
                }  
            };  
            futures.add(executorService.submit(task));  
        }  
          
        for (Future<String> future : futures) {  
            ret.append(future.get());  
        }  
        executorService.shutdown();  
          
        return ret.toString();  
    }  
}  

Callable与Future的介绍

Callable与 Future 两功能是Java在后续版本中为了适应多并法才加入的,Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其他线程执行的任务。

Callable的接口定义如下:

public interface Callable<V> { 
      V   call()   throws Exception; 
} 

Callable和Runnable的区别如下:

  1. Callable定义的方法是call,而Runnable定义的方法是run。

  2. Callable的call方法可以有返回值,而Runnable的run方法不能有返回值。

  3. Callable的call方法可抛出异常,而Runnable的run方法不能抛出异常。

Future 介绍

Future表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。Future的cancel方法可以取消任务的执行,它有一布尔参数,参数为 true 表示立即中断任务的执行,参数为 false 表示允许正在运行的任务运行完成。Future的 get 方法等待计算完成,获取计算结果

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
 * Callable 和 Future接口
 * Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。
 * Callable和Runnable有几点不同:
 * (1)Callable规定的方法是call(),而Runnable规定的方法是run().
 * (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
 * (3)call()方法可抛出异常,而run()方法是不能抛出异常的。
 * (4)运行Callable任务可拿到一个Future对象,
 * Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。
 * 通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。
 */
 
public class CallableAndFuture {
    public static class  MyCallable  implements Callable{
          private int flag = 0; 
          public MyCallable(int flag){
                  this.flag = flag;
          }
          public String call() throws Exception{
              if (this.flag == 0){  
                      return "flag = 0";
            } 
            if (this.flag == 1){   
                try {
                    while (true) {
                           System.out.println("looping.");
                            Thread.sleep(2000);
                    }
                } catch (InterruptedException e) {
                              System.out.println("Interrupted");
                }
                return "false";
            } else {   
                       throw new Exception("Bad flag value!");
            }
        }
    }
    public static void main(String[] args) {
       // 定义3个Callable类型的任务
        MyCallable task1 = new MyCallable(0);
        MyCallable task2 = new MyCallable(1);
        MyCallable task3 = new MyCallable(2);
       // 创建一个执行任务的服务
        ExecutorService es = Executors.newFixedThreadPool(3);
        try {
           // 提交并执行任务,任务启动时返回了一个Future对象,
            // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作
            Future future1 = es.submit(task1);
           // 获得第一个任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行
            System.out.println("task1: " + future1.get());
            Future future2 = es.submit(task2);
           // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环
            Thread.sleep(5000);
            System.out.println("task2 cancel: " + future2.cancel(true));
           // 获取第三个任务的输出,因为执行第三个任务会引起异常
            // 所以下面的语句将引起异常的抛出
            Future future3 = es.submit(task3);
            System.out.println("task3: " + future3.get());
        } catch (Exception e){
            System.out.println(e.toString());
        }
       // 停止任务执行服务
        es.shutdownNow();
    }
}

猜你喜欢

转载自blog.csdn.net/chenyao1994/article/details/84174156