在 Java 中以并行方式完全同时处理两个任务 [英] Processing two tasks exactly at the same time as parallel in Java

查看:53
本文介绍了在 Java 中以并行方式完全同时处理两个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to call 8 methods in a method.

这8个方法中的2个方法是一个空洞任务,剩下的6个方法是另一个空洞任务.

2 methods inside of these 8 methods is one hole task, and the remaining 6 methods is another hole task.

我想并行处理这两个任务.

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

据我所知,我可以用线程来完成.但老实说,要么我看不到与我的目标相似的示例,要么如果我看过,我无法理解该示例.

As I know I can do it with threads. But to be honest either I couldn't see an example which is similar to my goal, or I couldn't understand the example if I've seen.

您能否简要地向我展示一个示例,以便我完成目标?

Could you briefly show me an example in order me to finish my goal?

谢谢,

推荐答案

可能是这样的:

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

这篇关于在 Java 中以并行方式完全同时处理两个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆