Processing two tasks at exactly the same time as parallel in Java

I want to call 8 methods in a method.

The 2 methods inside these 8 methods are one hole task, and the remaining 6 methods are another hole task.

I want to handle these 2 tasks exactly at the same time as in parallel.

As I know, I can do this with threads. But honestly, I could not see an example similar to my goal, or I could not understand the example if I saw it.

Could you briefly show me an example to complete my goal?

Thank,

+4
source share
2 answers

Something like this is possible:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(final String[] args) throws InterruptedException {
        final ExecutorService pool = Executors.newFixedThreadPool(2);

        pool.execute(() -> {
            method1();
            method2();
        });

        pool.execute(() -> {
            method3();
            /* ... */
            method8();
        });

        pool.shutdown();

        if (!pool.awaitTermination(1, TimeUnit.DAYS))
            System.err.println("Pool did not terminate.");
    }
}
+3
source

This can be done in various ways, for example, using the general Semaphore:

public static class Task implements Runnable {

    Semaphore s;
    String name;

    public Task(Semaphore s, String name) {
        this.s = s;
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(name + " waiting");
        try {
            s.acquire();         // wait for permit
            System.out.println(name + " continuing");
        } catch (InterruptedException e) {
            System.out.println("Interrupted while waiting");
        }
    }
}

Semaphore :

Semaphore s = new Semaphore(0);
new Thread(new Task(s, "Task A")).start();
new Thread(new Task(s, "Task B")).start();
Thread.sleep(1000);
s.release(2);                  // release 2 permits to allow both threads continue

:

Task A waiting
Task B waiting
Task A continuing              // after 1 second
Task B continuing
+2

All Articles