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;
            }
        }

    }
}

 

posted @ 2020-09-07 16:18  PEAR2020  阅读(617)  评论(0编辑  收藏  举报