How to wait for all threads to finish, using ExecutorService?

前端 未结 26 2430
你的背包
你的背包 2020-11-22 01:55

I need to execute some amount of tasks 4 at a time, something like this:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    tas         


        
26条回答
  •  Happy的楠姐
    2020-11-22 02:46

    This is my solution, based in "AdamSkywalker" tip, and it works

    package frss.main;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TestHilos {
    
        void procesar() {
            ExecutorService es = Executors.newFixedThreadPool(4);
            List tasks = getTasks();
            CompletableFuture[] futures = tasks.stream().map(task -> CompletableFuture.runAsync(task, es)).toArray(CompletableFuture[]::new);
            CompletableFuture.allOf(futures).join();
            es.shutdown();
    
            System.out.println("FIN DEL PROCESO DE HILOS");
        }
    
        private List getTasks() {
            List tasks = new ArrayList();
    
            Hilo01 task1 = new Hilo01();
            tasks.add(task1);
    
            Hilo02 task2 = new Hilo02();
            tasks.add(task2);
            return tasks;
        }
    
        private class Hilo01 extends Thread {
    
            @Override
            public void run() {
                System.out.println("HILO 1");
            }
    
        }
    
        private class Hilo02 extends Thread {
    
            @Override
            public void run() {
                try {
                    sleep(2000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("HILO 2");
            }
    
        }
    
    
        public static void main(String[] args) {
            TestHilos test = new TestHilos();
            test.procesar();
        }
    }
    

提交回复
热议问题