我有一個整數陣列作為輸入,其大小可以在1和10^6之間變化:
eg.
int inputArr = new int[]{1, 2, 3, 4, 5}。
我在運行時動態地設定執行緒數,就像這樣:
我在運行時動態地設定執行緒數。
int threadCount = Runtime.getRuntime().availableProcessors() * 2;
執行緒的數量可以從4到64不等。這意味著,執行緒數可能會比inputArr的大小還要大,這取決于平臺的情況。
由于inputArr也可能變得相當大,我希望以小塊的方式并行處理inputArr。
到目前為止,我已經成功地創建了以下內容
public class Main {
public static void main(String[] args) {
int threadCount = Runtime.getRuntime().availableProcessors() * 2;
ExecutorService executor = Executors.newFixedThreadPool(threadCount)。
final var inputArr = new int[]{1, 2, 4, 5}。
for (int i = 0; i < threadCount; i ) {
executor.submit(new Worker(inputArr, i * threadCount, (i 1) * threadCount))。
}
執行器.關機()。
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)。
} catch (InterruptedException e) {
e.printStackTrace()。
}
}
private static class Worker implements Runnable {
private final int[] arr;
private final int start;
private final int end;
public Worker(int[] arr, int startIndex, int endIndex) {
this.arr = arr;
this.start = startIndex;
this.end = endIndex;
}
public void run() {
System.out.printf("Thread start: %d
", Thread.currentThread().getId())。
for (int i = this. start; i < this.end; i ) {
System.out.println(arr[i])。
}
System.out.printf("Thread end: %d
", Thread.currentThread().getId())。
}
}
}
而輸出結果與此類似:
...
執行緒開始。27
執行緒開始。34
主題開始。33
執行緒開始。24
1
2 2
4 4
5
執行緒開始。30
執行緒開始。26
...
很明顯,這里創建了許多執行緒。遠遠超過這個例子中我的inputArr的大小。
但相反,我希望輸出的結果是這樣的:
...
執行緒開始。X
1
2
4
5
執行緒結束。X
...
我認為我的問題是對陣列進行了錯誤的磁區。我做錯了什么?誰能幫幫我?
uj5u.com熱心網友回復:
你的磁區看起來并不正確,是的。
代替
for (int i = 0; i < threadCount; i ) {
executor.submit(new Worker(inputArr, i * threadCount, (i 1) * threadCount))。
試試這個
final var batchSize = inputArr. length / threadCount == 0 ? inputArr.length : inputArr.length / threadCount;
final var remainder = inputArr.length % threadCount;
final int partitionSize = threadCount > batchSize ? 1 : threadCount;
for (int i = 0; i < partitionSize; i ) {
int endIndex = (i 1)* batchSize。
executor.submit(new Worker(inputArr, i * batchSize, endIndex > inputArr.length ? remainder : endIndex))。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/308342.html
標籤:
