在 Java 中并行处理两个任务

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

我想在一个方法中调用8个方法

这8个方法里面的2个方法是一个洞任务,剩下的6个方法是另一个洞任务

我想同时并行处理这两个任务。

据我所知,我可以使用线程来完成。但老实说,要么我看不到与我的目标相似的例子,要么我看到了也无法理解这个例子。

你能简单地举个例子让我完成我的目标吗?

谢谢,

这可以通过多种方式完成,例如使用共享 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");
        }
    }
}

在主代码中,使用shared 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

可能是这样的:

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.");
    }
}