Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

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

Related questions

1 answer 47 views
1 answer 131 views
131 views asked Sep 28, 2019 by avibootz
1 answer 174 views
1 answer 261 views
1 answer 135 views
...