在Java中并行处理两个任务

时间:2015-05-15 10:36:26

标签: java parallel-processing

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

这8个方法中的2个方法是一个洞任务,其余6个方法是另一个洞任务。

我想在并行的同时完全处理这两项任务。

据我所知,我可以用线程来做。但老实说,要么我看不到一个与我的目标相似的例子,要么就是我看不懂这个例子。

你能简单地告诉我一个例子,以便我完成目标吗?

谢谢,

2 个答案:

答案 0 :(得分:3)

这样的事情可能是:

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

答案 1 :(得分:2)

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