Reputation: 147
I need to separate an array considering count of threads. For example i have the array [1][2][3][4][5][6][7][8][9][10] and user print count of thread which will be work with elements in this array. My task is distribute the work between arrays' elements and threads.
Count of threads = 2 -> thread1:[1][2][3][4][5] thread2:[6][7][8][9][10]. But what i need to do if threads will be for instance 7. Ho to separate work in this case?
Upvotes: 0
Views: 677
Reputation: 24145
here is sample application which splits input array to threads:
final int threadCount = 7;
final int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int from = 0;
for (int i = 0; i < threadCount; i++) {
final int to = (from + (int) Math.ceil((a.length - from) / (double) (threadCount - i)));
System.out.println("Thread #" + i + " will use " + Arrays.toString(Arrays.copyOfRange(a, from, to)));
from = to;
}
actually (thanks to @Andreas), instead of ceiling, you can use simply integer math:
final int to = from + ((a.length - from) / (threadCount - i));
output:
Thread #0 will use [1, 2]
Thread #1 will use [3, 4]
Thread #2 will use [5, 6]
Thread #3 will use [7]
Thread #4 will use [8]
Thread #5 will use [9]
Thread #6 will use [10]
Upvotes: 2