blauerschluessel blauerschluessel - 5 months ago 8
Java Question

I don't understand threads

Let's say I am given a function

Data[] foo(double[] someNumbers, Data[] someData, AnalyzeTool tool, int numOfThreads)

, the array's having the same length len.

Now I would like to invoke numOfThreads threads in the method using tool to process each one Data.Object and write it one of another back into an Data[], so that the Data[] given and Data[] written stays in order.

Let's say a thread is now finished processing one Data Object, how do I tell this thread, that there is still data left, that isn't yet processed and assign and "lock" a next Data Object to process it? "Locking" should prevent that on Data Object is processed several times by multiple threads.

Does someone have an example how to do that? Any sort of constructive help is welcome.


Being new to multi-threading, in my experience i would have done something like this:

Considering i have a lot of task to be done with each Data[] item. let us say every data item is a work.

ExecutorService provides you with a factory where there is a group of workers (Thread pools) to help you complete all of your work, the Executor service allocates work to each of the worker(Thread) one by one, as soon as anyone of them finishes, and more work is there, they are allocated with that.

consider this example:

ExecutorService executor = Executors.newFixedThreadPools(5);
//lets say we have 5 workers with us.

//then submitting all your work (a runnable) to the factory
for(int i=0;i<n;i++){
    executor.submit(new work(someData[i]));

Executor will start doing the work as you submit and then picks up the next from the pool.... and so on.

simply then,