博客
关于我
JAVA定义一个线程池,循环遍历list
阅读量:604 次
发布时间:2019-03-12

本文共 3421 字,大约阅读时间需要 11 分钟。

文章目录

前言

如果要处理一千条数据,你可能需要瞬间启动一千个线程。然而,需要仔细处理主线程与子线程之间的同步问题。而你的代码最大的问题在于,如何让主线程能够方便地获取子线程的处理结果。这种场景在实际项目中尤为重要。

思路

  • 将需要15秒左右完成的任务放入一个类中,实现Callable接口,这个任务我们称之为一个任务。
  • 然后,你已经有了一个List,可以遍历这个List,构建一个任务数组。
  • 创建ConcurrentExcutor对象并执行数组中的任务。
  • ProcessNumTask[] tasks = new ProcessNumTask[tempList.size()]; for(int i=0; i ce = new ConcurrentExcutor(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;public class ConcurrentExcutor { private Callable[] tasks; private int numb; private List result; public ConcurrentExcutor() {} public ConcurrentExcutor(Callable[] tasks, int numb) { super(); this.tasks = tasks; this.numb = numb; } public ConcurrentExcutor(Callable[] tasks, int numb, List 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; for(int i=0; i < (num/numb)+1; i++) { ExecutorService es = Executors.newCachedThreadPool(); Future[] futureArray = new Future[num]; for(int j=i*numb; j<(i+1)*numb; j++) { if(j+1 > num) break; futureArray[j%numb] = es.submit(tasks[j]); } if(result != null) { for(Future
    future : futureArray) { try { if(future != null) { T o = future.get(); result.add(o); } } catch(InterruptedException e) { System.out.println("处理Future时发生InterruptedException异常:" + future.toString()); e.printStackTrace(); } catch(ExecutionException e) { System.out.println("处理Future时发生ExecutionException异常:" + future.toString()); e.printStackTrace(); } } } es.shutdown(); } }}

    Callable与Future介绍

    Callable和Future是Java在后续版本中为了适应多线程环境而引入的接口。Callable类似于Runnable,但它可以定义一个返回值的方法call(), 而Runnable只能执行无返回值的run()方法。此外,Callable的call()方法可以抛出异常,而Runnable则不行。

    Callable接口定义

    public interface Callable { T call() throws Exception; }

    Callable与Runnable的区别

  • Callable定义了call()方法,而Runnable定义了run()方法。
  • Callable的call()方法可以返回值,而Runnable的run()方法不能。
  • Callable的call()方法可以抛出异常,而Runnable的run()方法不能。
  • Future的介绍

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

    示例代码解析

    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 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 list, final int nThreads) throws Exception { if(list == null || list.isEmpty()) return ""; StringBuffer ret = new StringBuffer(); ExecutorService executorService = Executors.newFixedThreadPool(nThreads); List> futures = new ArrayList<>(); for(int i=0; i subList = list.subList(i * list.size() / nThreads, (i+1) * list.size() / nThreads); Callable task = new Callable() { @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 future : futures) { ret.append(future.get()); } executorService.shutdown(); return ret.toString(); } }}

    转载地址:http://jhixz.baihongyu.com/

    你可能感兴趣的文章
    Objective-C实现实现rabin karp算法(附完整源码)
    查看>>
    Objective-C实现对图像进行色调处理算法(附完整源码)
    查看>>
    Objective-C实现对称矩阵压缩存储(附完整源码)
    查看>>
    Objective-C实现寻找Find Lcm最小公倍数算法(附完整源码)
    查看>>
    Objective-C实现寻找欧拉路径/回路(附完整源码)
    查看>>
    Objective-C实现导弹跟踪算法(附完整源码)
    查看>>
    Objective-C实现将 b 除以模 n 的有效算法(附完整源码)
    查看>>
    Objective-C实现将 base64 字符串转换为字节数组算法(附完整源码)
    查看>>
    Objective-C实现将位转换为浮点数bitsToFloat算法(附完整源码)
    查看>>
    Objective-C实现将列表向右旋转 k 个位置算法(附完整源码)
    查看>>
    Objective-C实现将字符串中大写字母转换为小写字母(附完整源码)
    查看>>
    Objective-C实现将字符串从一个基转换为另一个基算法(附完整源码)
    查看>>
    Objective-C实现将字节数组转换为 base64 编码算法(附完整源码)
    查看>>
    Objective-C实现将彩色图像转换为负片算法(附完整源码)
    查看>>
    Objective-C实现将无符号整数n变成成d进制表示的字符串s(附完整源码)
    查看>>
    Objective-C实现将给定的 utf-8 字符串编码为 base-16算法(附完整源码)
    查看>>
    Objective-C实现将给定的字符串编码为 base32算法(附完整源码)
    查看>>
    Objective-C实现小根堆(附完整源码)
    查看>>
    Objective-C实现局域网双向通信(附完整源码)
    查看>>
    Objective-C实现局部最大值点数算法(附完整源码)
    查看>>