How to execute 3 functions concurrently in Java

1 Answer

0 votes
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.List;

class Execute3FunctionsConcurrently {

    public static void main(String[] arg) throws Exception {
        long start = System.currentTimeMillis();
        
        List<Future<String>> r;
        try (ExecutorService executorService = Executors.newFixedThreadPool(3)) {
            r = executorService.invokeAll(List.of(
                Execute3FunctionsConcurrently::f1,
                Execute3FunctionsConcurrently::f2,
                Execute3FunctionsConcurrently::f3
            ));
        }
        
        long end = System.currentTimeMillis();

        String r1 = r.get(0).get();
        String r2 = r.get(1).get();
        String r3 = r.get(2).get();
        
        System.out.println("Duration: " + (end - start) + "ms");
        
        System.out.println("r1 = " + r1);
        System.out.println("r2 = " + r2);
        System.out.println("r3 = " + r3);
    }

    static String f1() {
        simulateWork(300);
        return "f1()";
    }
    
    static String f2() {
        simulateWork(500);
        return "f2()";
    }
    
    static String f3() {
        simulateWork(100);
        return "f3()";
    }

    static void simulateWork(int ms) {
        try {
            Thread.sleep(ms);
        } catch(InterruptedException e) {}
    }
}



/*
run:

Duration: 504ms
r1 = f1()
r2 = f2()
r3 = f3()

*/

 



answered Sep 16, 2025 by avibootz
...