【问题标题】:Running a compiler in parallel with java.utils.concurrent与 java.utils.concurrent 并行运行编译器
【发布时间】:2021-12-28 16:17:53
【问题描述】:

我正在为 Java 语言制作编译器,我希望它能够并行编译许多文件。

我的班级Compiler.java 有构造函数Compiler(String fileName) 和方法compile() 所以要在我的 main 中编译一个文件,我所做的就是:

Compiler c1 = new Compiler("file1.c");
c1.compile();

我想要做的是一个文件列表(比如说 ["file1.c", "file2.c", "file3.c"] )正在执行 c1.compile(), c2.compile( ), c3.compile() 并行(c'i' 是 file'i' 的编译器)。

我还是Java.util.concurrent 的初学者。在 C 语言中,我只是 fork 或使用带有 join 方法的 POSIX 线程库。但是在 Java 中,我发现还有更多关于线程池等的东西。任何帮助都将不胜感激。

【问题讨论】:

  • 线程池并不是 Java 独有的。尽管在某些语言中,标准库具有一种或多种线程池类型,但在 C 或 C++ 中,您仍然必须使用第 3 方库,或者自行开发。跨度>
  • 线程池的想法是通过重复使用它们来避免在服务器环境中创建线程并在每个请求中将其拆除一次的开销。对于编译器,这可能不适用。只需根据需要创建和退出线程。

标签: java multithreading java.util.concurrent java-threads


【解决方案1】:

如果你想要的只是一个线程,你没有在 Java 中使用线程池。*(假设你想使用线程**)几乎是最简单的创建方法一个线程看起来像这样:

    Thread t = new Thread(() -> {
        ...code to be executed in the new thread goes here...
    });
    t.start();
    ...do other stuff concurrently with the new thread...
    try {
        t.join();
    } catch (InterruptedException ex) {
        // If your program doesn't use interrupts then this should
        // never happen. If it happens unexpectedly then, Houston! We
        // have a problem...
        ex.printStackTrace();
    }

* 如果您的程序会创建许多短期线程,您可能想要使用线程池。与任何其他类型的“xxxx 池”一样,线程池的目的是重复使用线程,而不是不断地创建和销毁它们。与某些程序想要在这些线程中运行的任务的成本相比,创建和销毁线程的成本相对较高。

使用线程池的最简单的方法如下所示:

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

    final int N_THREADS = ...however many worker threads you think you need...;
    final int PRACTICALLY_FOREVER = 999;

    ExecutorService thread_pool = Executors.newFixedThreadPool(N_THREADS);
    while (...still have work to do...) {
        thread_pool.submit(() -> {
            ...task to be executed by a worker thread goes here...
        });
    }
    thread_pool.shutdown();
    try {
        thread_pool.awaitTermination(PRACTICALLY_FOREVER, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        // If your program doesn't use interrupts then this should
        // never happen...
        ex.printStackTrace();
    }

** 有些人认为线程是老式的和/或低级的。 Java 有一个完全不同的并发模型。您可能需要一些时间来了解parallel streams

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2010-10-25
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多