zoukankan      html  css  js  c++  java
  • ExecutorService线程池submit的使用

    有关线程池ExecutorService,只谈submit的使用

    可创建的类型如下:

    private static ExecutorService pool = Executors.newFixedThreadPool(20);//创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

    private static ExecutorService pool1 = Executors.newCachedThreadPool();//创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

    private static ExecutorService pool2 = Executors.newScheduledThreadPool(20);//创建一个定长线程池,支持定时及周期性任务执行。

    private static ExecutorService pool3 = Executors.newSingleThreadExecutor();//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    在使用多线程时需要每个线程的返回值,了解到自己的类实现Callable接口可以实现,所以就写了测试用例,但是测试时发现基本都是有序执行。经过多处查证,发现端倪。

    1.启动线程时会返回一个Future对象。

    2.可以通过future对象获取现成的返回值。

    3.在执行future.get()时,主线程会堵塞,直至当前future线程返回结果。

    也是因为第三点,导致我每次运行都是顺序执行。。。。。

    说一下submit(Callable<T> task)的用法。

    Future<Integer> result = pool.submit(new ThreaTest());会返回一个自定义类型的Future对象。

    注意,如果调用result.get()方法,会阻塞主线程,最坏的结果是所有线程顺序执行。

    程序执行完后记得shutdown。

    自己的类implements Callable<Integer>,并重写call方法,在call方法里完成业务逻辑,并添加返回值。完整代码如下:

    import java.util.ArrayList;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class ThreaTest implements Callable<Integer> {
        private int nowNumber = 0;
        private static ExecutorService pool = Executors.newFixedThreadPool(20);// 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
    
        public ThreaTest(int nowNumber) {
            this.nowNumber = nowNumber;
        }
    
        public static void main(String[] args) {
            ArrayList<Future<Integer>> result = new ArrayList<Future<Integer>>();
    
            for (int i = 0; i < 5000; i++) {
                Future<Integer> submit = pool.submit(new ThreaTest(i));
                result.add(submit);
            }
    
            pool.shutdown();
        }
    
        public Integer call() throws Exception {
            System.out.println(this.nowNumber);
            return this.nowNumber;
        }
    }
  • 相关阅读:
    【转】批处理第三方命令行工具汇总(2014-11-10更新)
    爬虫问题汇总 + 解决
    ocs的沟通平台
    DSCP 与IP 优先级IP优先级
    IPSec协议
    GRE 协议简介
    使用VLC创建组播流
    华为olt ma5680t常用命令详解
    Python统计列表中的重复项出现的次数的方法
    Kafka
  • 原文地址:https://www.cnblogs.com/chxwkx/p/11225989.html
Copyright © 2011-2022 走看看