我正在為 Java 語言制作一個編譯器,我希望它并行編譯許多檔案。
我的類Compiler.java有建構式Compiler(String fileName)和方法compile()
所以要在我的主要檔案中編譯單個檔案,我所做的就是:
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. 在 CI 中只需 fork 或將 POSIX 執行緒庫與join方法一起使用。但是在 Java 中,我看到還有更多的東西叫做執行緒池等。任何幫助將不勝感激。
uj5u.com熱心網友回復:
你不具備使用執行緒池在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 有一個完全不同的并發模型。您可能需要花一些時間來了解并行流。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/403040.html
標籤:
上一篇:JavaFX:“JavaFX應用程式執行緒中的例外java.lang.RuntimeException:java.lang.reflect.InvocationTargetException”Java
