V
V
VasG2011-10-18 20:09:37
Java
VasG, 2011-10-18 20:09:37

How do you know in Java that a thread has finished executing?

I just started using these streams yesterday, and I'm still "off topic".
I would like to organize batch processing of images, and for this two threads were made: thrProcess and thrUpdateUI , respectively, to perform image processing and update the interface (adding reduced copies of the result). Moreover, the second one is launched from the first one (it just says thrUpdateUI.start() at the end )
There is an array that stores absolute paths to images: imgToProcPath[] .
Actually, that's all, the flows are described above, and I'm trying to start them:

for (int i = 0; i < imgToProcPath.length; i++) {
    thrProcess.start();
}

(if you can’t do this in any case - a big request not to sharpen the pitchfork on me right away)
But for some reason only one thread (zero) is called.
Maybe there is a way to wait until both threads are completed and then proceed to the next iteration? But how?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sainnr, 2011-10-18
@VasG

From what I understand, you have a slightly misunderstanding about threads. In the code you provided, the same thrProcess thread is given the command to run on each iteration . Why run it multiple times if it has already executed start() after the first iteration (with i = 0)?
In this case, you can:
1) move the loop that goes through all the images in the array inside the thread's worker method thrProcess and run this thread once ; 2) create a new thread (thrProcess1, thrProcess2, ..., thrProcessN)
in the loop at each iteration , in which the current image will be processed, and run it.
The second option is very strange - agree, if you have 1000 images, then create 1 thread for each of them, i.e. 1000 threads in total will somehow not be good.

R
romik, 2011-10-18
@romik

One Thread object is one thread, even if you call start multiple times. In your case, it makes sense to use a higher-level abstraction like ExecutorService .

ExecutorService  executor =  Executors . newFixedThreadPool ( 4 ) ;
List < Future < MyResult >>  futures =  new  ArrayList <> ( ) ;
for  ( File  path: imgToProcPath )  {
    executor. submit ( new  MyImageProcessingTask ( path ) ;
}
for  ( Future < MyResult >  future: futures )  {
   displayThumbnail ( future. get ( ) ) ;
}

@
@antoo, 2011-10-18
_

for (int i = 0; i < 10; i++)
            {
                
                Thread thread = new Thread(new ThreadStart(ФУНКЦИЯ ВЫПОЛНЯЮЩАЯСЯ В ПОТОКЕ));
                thread.Name = Convert.ToString(i);
                thread.Start();
            }

And don't forget to check imgToProcPath.length;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question