zoukankan      html  css  js  c++  java
  • java提供的线程池的使用

    应用场景,比如你有个业务模块,非常耗时,并且还需要重复调用5次。

    如果你写个for循环调用5次,调用一次3秒,那么5次就15秒,不是很友好。

    这时,如果你用线程池就方便了,多线程跑,都跑完,收集到结果,也就是一个任务的时间。

    Demo:

    package com.tech.jin.thread;
    
    import java.util.ArrayList;
    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;
    
    public class TestThread {
    
        public void test(){
            int threadCount = 5;//创建线程数
            
            ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
            
            List<Future> list = new ArrayList<Future>();
            
            long time1 = System.currentTimeMillis();
            
            for(int i=0;i<threadCount;i++){
                //如果你有一个任务调用接口
                Callable c = new testCallable(i,time1);
                Future f = executorService.submit(c);//这里也可以submit(Thread或Runnable)
                
                list.add(f);
            }
            
            for(Future f :list){
                try {
                    long time3 = (Long)f.get();
                    System.out.println(time3);
                } catch (InterruptedException e) {
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            
        }
        
        
        public static void main(String[] args) {
            TestThread t = new TestThread();
            t.test();
        }
        
    }
    
    class testCallable implements Callable{
        private int i;
        private long time1;
        
    
        public testCallable(int i,long time1) {
            this.i = i;
            this.time1 = time1;
        }
    
    
        @Override
        public Object call() throws Exception {
            Thread.sleep(5000-(i*1000));
            long time2 = System.currentTimeMillis();
            
            long time3 = time2-time1;
            
            System.out.println(i+"------"+time3);
            
            return time3;
        }
        
    }

    我们故意让前边的sleep时间长点,让后边的先执行。

    结果:

    4------1006
    3------2006
    2------3006
    1------4005
    0------5004
    5004
    4005
    3006
    2006
    1006

    跑完发现List<Future> list中存放的顺序还是按照原顺序来的,所以不用担心顺序问题。

  • 相关阅读:
    JS leetcode 买卖股票的最佳时机 题解分析,我离职了。
    JS leetcode x 的平方根 题解分析
    JS leetcode 有多少小于当前数字的数字 解题分析,你应该了解的桶排序
    JS leetcode 合并两个有序数组 解题分析
    JavaSE部分 (多线程下)
    JavaSE部分 (多线程上)
    JavaSE部分 (异常)
    JavaSE部分 集合下(Map)
    JavaSE部分 集合中(数据结构 list set Collections)
    JavaSE (接口 final 内部类)
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/6278899.html
Copyright © 2011-2022 走看看