0

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?

2
  • 1
    [1][2][3][4][5][6][7][8][9][10] is a 10-dimensional array, not a single array of 10 elements. {1,2,3,4,5,6,7,8,9,10} is a single array with 10 elements. Commented May 3, 2016 at 20:42
  • How about using an ExecutorService with a Threadpool that have the required number of threads? Like ExecutorService pool = Executors.newFixedThreadPool(poolSize). Then, you can submit the tasks by iterating though the array and submitting each element as a parameter to a runnable task. Take a look at docs.oracle.com/javase/7/docs/api/java/util/concurrent/… Commented May 3, 2016 at 20:59

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

6 Comments

I like Math.round() better. ;-)
@Andreas math.round will not work, for example 11 elements and 10 threads
It works. Try it. You can even do Math.floor(). Why should the first threads get all the fun?
@Andreas oh, you're right, you can do floor or round
You can see the difference between ceil(), round(), and floor() in this IDEONE demo.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.