zoukankan      html  css  js  c++  java
  • Java线程池ExecutorService 代码备忘

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5)
    创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
    package UnitTest;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class test {
        public static void main(String[] args) {
            int flag = 0;
            long a = System.currentTimeMillis();
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
            List<Future> resultList = new ArrayList<>();
            for (int i = 1; i < 101; i++) {
                Future future = fixedThreadPool.submit(new ThreadWithRunnable(i));
                resultList.add(future);
            }
            fixedThreadPool.shutdown();
    
            for (Future fs : resultList) {
                try {
                    System.out.println(fs.get().toString());
                    flag += Integer.parseInt(fs.get().toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println(flag);
            System.out.println("
    <br>执行耗时 : " + (System.currentTimeMillis() - a) / 1000f + " 秒 ");
    
        }
    }
    package UnitTest;
    
    import java.util.concurrent.Callable;
    
    public class ThreadWithRunnable implements Callable {
        private int number;
        public ThreadWithRunnable(int number){
            this.number = number;
        }
    
        @Override
        public Object call() throws Exception {
            for (int i=1;i<1000;i++){
                Thread.sleep(1);
            }
            return number;
        }
    }
  • 相关阅读:
    设计模式之原型模式
    设计模式之建造者模式
    一个工厂还能写出花来?
    一个单例还能写出花来?
    python基础之条件循环语句
    python基础之七种运算符
    python基础之五大标准数据类型
    node.js express mvc轻量级框架实践
    js Date() 浏览器兼容问题解决
    js 倒计时(服务器时间同步)
  • 原文地址:https://www.cnblogs.com/kgdxpr/p/10383291.html
Copyright © 2011-2022 走看看