博客
关于我
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/

    你可能感兴趣的文章
    Python3学习笔记(urllib模块的使用)
    查看>>
    python3安装scapy_Linux下安装scapy-python3
    查看>>
    python3实现socket通信
    查看>>
    Python关于numpy.transpose函数详细解析附代码
    查看>>
    Python3导入自定义模块的3种方式
    查看>>
    python3打开txt文件_使用Python 3从文本文件读取句子并添加到列表中
    查看>>
    python3爬虫抓取智联招聘职位信息代码
    查看>>
    Python3爬虫数据入数据库---把爬取到的数据存到数据库,带数据库去重功能
    查看>>
    python3的 pymysql把mysqldb库取代了,让python 3支持mysqldb的解决方法
    查看>>
    Python3笔记——IDE的选择
    查看>>
    python3简单使用requests 用户代理,cookie池
    查看>>
    Python3组播通信编程实现教程(发送者+接收者)
    查看>>
    Python3编写网络爬虫10-数据存储方式三-CSV文件存储
    查看>>
    python3读取redis返回数据带有'b'的问题
    查看>>
    Python3连接MySQL
    查看>>
    Python关于isinstance函数的解析 | 附Demo(全)
    查看>>
    Python3:setup.py:完成所有任务的PIP安装(Build_ext+Install)
    查看>>
    python4.0 gil_Python 并发编程系列--1、浅谈GIL历史及对多线程的影响
    查看>>
    python60行绘图程序_天底下最简单的QT画图板,就一个类,60行代码
    查看>>
    Python: AES加密与解密
    查看>>