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中存放的顺序还是按照原顺序来的,所以不用担心顺序问题。

  • 相关阅读:
    tensorflow2.0——动量,动态学习率,Dropout
    tensorflow2.0——过拟合优化regularization(简化参数结构,添加参数代价变量)
    tensorflow2.0——自定义全连接层实现并保存
    关于生成器的问题
    端午节大礼包(投票系统)
    写一个函数完成三次登陆功能,再写一个函数完成注册功能
    例题练习
    文件操作
    解决列表中增加字典覆盖之前相同key的字典
    字符串操作,列表,元组,字典操作
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/6278899.html
Copyright © 2011-2022 走看看