zoukankan      html  css  js  c++  java
  • FixedThreadPool Executors

    public class T05_ThreadPool {
    
        public static void main(String[] args) throws InterruptedException {
    
            ExecutorService service = Executors.newFixedThreadPool(5); // 固定长度的线程池
            for (int i = 0; i < 6; i++) { // 执行六个任务,  在只有五个固定容量的线程池中
                service.execute(() -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
            System.out.println(service); // [Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
            // 内部一般是BlockingQueue
            // pool size =  5  线程池的容量
            // active thread = 5 激活的线程队列长度
            // queued tasks = 1 等待处理任务长度
            // completed task = 0 完成执行的任务数量
            
            // 关闭线程池
            service.shutdown(); // 未执行完毕,不会停止,只会进入停止中状态
            System.out.println(service.isTerminated()); // false 是否结束
            System.out.println(service.isShutdown()); // true 状态是否关闭
            System.out.println(service);  //java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
            
    
            TimeUnit.SECONDS.sleep(5); // 5s 后肯定执行完成了
    
            System.out.println(service.isTerminated()); // true 
            System.out.println(service.isShutdown()); // true
            System.out.println(service); // java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
    
            
            // 线程池中维护了两个任务队列
            // 1. 未执行的任务队列
            // 2. 已执行的任务队列
        }  
    }

    线程池的作用:并行计算

    /**
     * 线程池的作用:并行计算
     * 计算 1-200000 之间的质数
     */
    public class T07_ParallelComputing {
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            long start = System.currentTimeMillis();
            List<Integer> result = getPrime(1, 200000);
            long end = System.currentTimeMillis();
            System.out.println("主线程"+(end - start)); // 使用单线程计算的时间
    
            ExecutorService service = Executors.newFixedThreadPool(3);
            ComputeTask t1 = new ComputeTask(1, 100000);
            ComputeTask t2 = new ComputeTask(16000, 190000);
            ComputeTask t3 = new ComputeTask(190001, 200000);
            ComputeTask t4 = new ComputeTask(100001, 160000);  // 这里为什么不均分? 因为数字越大, 质数的数量就越多
            // 提交任务给ExecutorService执行
            Future<List<Integer>> f1 = service.submit(t1);
            Future<List<Integer>> f2 = service.submit(t2);
            Future<List<Integer>> f3 = service.submit(t3);
            Future<List<Integer>> f4 = service.submit(t4);
            // 执行开始
            start = System.currentTimeMillis();
            f1.get();
            f2.get();
            f3.get();
            f4.get();
            end = System.currentTimeMillis();
            System.out.println(end - start);
            service.shutdown();
        }
    
        static class ComputeTask implements Callable<List<Integer>> {
    
            private int start, end;
            
            ComputeTask (int start, int end) {
                this.start = start;
                this.end = end;
            }
    
            @Override
            public List<Integer> call() throws Exception {
                return getPrime(start, end);
            }
        }
        
    
        static boolean isPrime(int num) {
            for (int i = 2; i < num / 2; i++) {
                if (num % i == 0) return false;
            }
            return true;
        }
    
        /**
         * 返回指定范围的质数列表
         */
        static List<Integer> getPrime(int start, int end) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < end; i++) {
                if (isPrime(i)) list.add(i);
            }
            return list;
        }
    }
  • 相关阅读:
    软件工程课堂二
    大二下学期第三周总结
    大二第二个学期的自我介绍
    如何将非ARC的项目转换成ARC
    UIScrollView
    关于nil和 null和NSNull的区别及相关问题
    提高iOS开发效率的第三方框架等--不断更新中。。。
    iOS中常见的设计模式(MVC/单例/委托/观察者)
    TCP/IP、Http、Socket的区别
    iOS使用AVFoundation实现二维码扫描
  • 原文地址:https://www.cnblogs.com/gxlaqj/p/11700291.html
Copyright © 2011-2022 走看看