executorService.invokeAll执行一批任务

|-- src                                                                         
|   |-- main                                                                    
|   |   |-- java                                                                
|   |   |   |-- Main.java                                                       
|   |   |   `-- ThreadDto.java                                                  

|-- src
|   |-- main
|   |   |-- java
|   |   |   |-- Main.java

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<ThreadDto> list = new LinkedList<>();
        for (int i = 0; i < 5; i++) {
            list.add(new ThreadDto());
        }

        executorService.invokeAll(list);
        //执行完毕就关闭线程池
        executorService.shutdown();
        System.out.println("end");
    }
}

/*
xxpool-1-thread-5
xxpool-1-thread-4
xxpool-1-thread-1
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-1
xxpool-1-thread-4
xxpool-1-thread-5
xxpool-1-thread-4
xxpool-1-thread-1
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
 */


|   |   |   `-- ThreadDto.java

import java.util.concurrent.Callable;

public class ThreadDto implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println("xx" + Thread.currentThread().getName());
        }
        return true;
    }
}

上一篇:JUC编程(六)-线程池


下一篇:java多线程