• 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;
        }
    }
  • 相关阅读:
    C++编程入门题目--No.5
    C++编程入门题目--No.4
    C++编程入门题目--No.3
    C++编程入门题目--No.2
    C++入门编程题目 NO.1
    深度使用魅族16T后的评价(本人魅友,绝对客观公正,不要盲目的为手机厂商辩护,想想从当初到现在,魅族正在一步步背离自己的信仰,有问题,解决问题才能有更好的发展)
    ACM及各类程序竞赛专业术语
    python刷LeetCode:3.无重复字符的最长子串
    python刷LeetCode:2.两数相加
    python刷LeetCode:1.两数之和
  • 原文地址:https://www.cnblogs.com/chxwkx/p/11225989.html
Copyright © 2020-2023  润新知