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;
            }
    
        }
  • 相关阅读:
    git的使用
    每个JavaScript开发人员应该知道的33个概念
    JavaEE实战——XML文档DOM、SAX、STAX解析方式详解
    Java-函数式编程(三)流(Stream)
    Spring高级装配(二) 条件化的bean
    Spring高级装配(一) profile
    Spring Bean装配学习
    Java7任务并行执行神器:Fork&Join框架
    Stream:java1.8新特性
    java基础
  • 原文地址:https://www.cnblogs.com/zgzf/p/10254587.html
Copyright © 2011-2022 走看看