简体   繁体   中英

Java, wait to launch a thread, till an equal instance has finished

I am pretty new with threads concurrency in Java. I have been looking around but I am still confused.

for (MyObj instance : allMyObjs) {
        instance.getAStoppableThreadObject.start();
    }

This will launch as many threads as in the allMyObjs list simultaneously. I need the loop to wait till the previous one has finished. Here below I made a quick and dirty example but I am looking for advise on how to improve it.

   for (MyObj instance : allMyObjs) {
        instance.getAStoppableThreadObject.start();
        while(instance.getAStoppableThreadObject.isAlive())
        {
            System.out.println("go to the bar and wait....");
        }
    }

Thanks

The join() method is used to have one thread wait for another thread to finish.

for (MyObj instance : allMyObjs) {
     instance.getAStoppableThreadObject.start();

     System.out.println("Thread started. Waiting til finished..");
     instance.getAStoppableThreadObject.join(); //will wait until its finished
     System.out.println("Thread has finished");
}

I agree with the comment that this might not be needed if you want sequential processing. Instead you might need one thread that you pass allMyObjs as parameter and the thread processing one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM