zoukankan      html  css  js  c++  java
  • Java 之 应用多线程计算1+2+...+100之多种方法比较(二)

    package com.njbdqn;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TenThreadPool extends Thread  {
        private static int[] counts = new int[10];
    
        @Override
        public void run() {
    
            System.out.println(Thread.currentThread().getName());
            // pool-1-thread-1 是线程池起线程的名称
                int x = Integer.parseInt(Thread.currentThread().getName().split("-")[3])-1;
                int y = x*10+1; // y决定每次加的起始值:1-10,11-20,21,...,91-100
                for (int i = y; i < y+10; i++) {
                    counts[x]+=i;
            }
    
        }
    
        public static void main(String[] args) {
            int total = 0;
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            for (int i = 0; i <10 ; i++) {
                executorService.submit(new TenThreadPool());
            }
            // 等待所有线程结束:可以使用线程池中的shutdown配合isterminated
    
            //Initiates an orderly shutdown in which previously submitted
            // tasks are executed, but no new tasks will be accepted.
            // 此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。
            executorService.shutdown();
            while (true){
                if(executorService.isTerminated()){
                    for (int i = 0; i <counts.length ; i++) {
                        System.out.println(counts[i]);
                        total+= counts[i];
                    }
                    System.out.println("total="+total);
                    break;
                }
            }
    
        }
    }
  • 相关阅读:
    后台跨域(CORS)
    golang 处理TCP粘包问题
    使用axios 发送ajax 下载文件
    Golang:在Redigo的RedisPool上选择DB
    puppeteer添加代理
    mongodb 权限操作
    alpine下安装icu-dev
    golang 导出CSV文件中文乱码的问题
    shell笔记
    Convert rune to int
  • 原文地址:https://www.cnblogs.com/sabertobih/p/13627528.html
Copyright © 2011-2022 走看看