zoukankan      html  css  js  c++  java
  • Java 线程池

    1.线程池

    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(60), new ThreadPoolExecutor.AbortPolicy());

    2.异步执行(主线程执行完了,子线程还没执行完)

    public void testPool() throws InterruptedException {
            System.out.println("======start=======");
            for (int i = 0; i < 10; i++) {
                final int key = i;
                threadPoolExecutor.execute(() -> {
                    test(key);
                });
            }
            System.out.println("=========end========");
    }

    3.主线程等待子线程执行完

    public void testPool() throws InterruptedException {
            System.out.println("======start=======");
            for (int i = 0; i < 10; i++) {
                final int key = i;
                threadPoolExecutor.execute(() -> {
                    test(key);
                });
            }
            threadPoolExecutor.shutdown();
            System.out.println("=========end========");
    }

     4.执行带返回值的

    public void testPool() throws InterruptedException, ExecutionException {
            System.out.println("======start=======");
            int result = 0;
            for (int i = 0; i < 10; i++) {
                final int key = i;
                Callable<Integer> callable = () -> test(key);
                Future<Integer> num = threadPoolExecutor.submit(callable);
                if (num.get() != null) {
                    result = num.get();
                }
            }
            System.out.println("=====result====" + result);
            threadPoolExecutor.shutdown();
            System.out.println("=========end========");
        }
    
        private Integer test(int key) {
            System.out.println("=============" + key);
            if (key == 8) {
                System.out.println("====key===");
                return key;
            } else {
                return null;
            }
    
        }
  • 相关阅读:
    了解Django之前
    jQuery
    java模板模式项目中使用--封装一个http请求工具类
    spring boot项目配置RestTemplate超时时长
    TortoiseSVN-1.7.12.24070-x64-svn-1.7.9安装包和汉化包
    ubuntu16.04环境下在docker上部署javaweb项目简单案例
    工厂模式
    面向对象第四次博客
    面向对象第三次作业总结
    oo第二次博客
  • 原文地址:https://www.cnblogs.com/zgzf/p/10254587.html
Copyright © 2011-2022 走看看