简体   繁体   中英

What actually happens after Thread.join()?

I have a program that parse a lot of txt files, so I wanted to do some multithreading to parse couple of files at the same time. What I did: created some threads for couple of files (example:3 threads for 3 files) and then in loop I added thread.join(). after they are done, I create threads for another files, doing join() again, again, again... I know that join() waits for each thread to do his job, but after that what happens to this thread? Does it makes room for another one, or is it still alive but doing nothing? I want only these couple threads to be alive at a time. I don't want situation where adding new ones just makes them stack.

When you call join() on an instance of Thread , the current thread is waiting that the job of the thread instance is done.

For your purpose, using Thread methods is not the easiest.

Please consider using an ExecutorService (made for managing threads with a specific policy) :

// You can easily create a service which runs tasks over many threads
ExecutorService service = Executors.newCachedThreadPool(); 
// Just put your task to run
service.submit( /* Runnable or Callable */ );
// Shutdown the service after (it will wait for current tasks terminaison)
service.shutdown();

If you need a callback, you can also use CompletableFuture :

CompletableFuture.runAsync( /* Runnable */ )
                 .thenRun( /* Your callback when task is over */ );

It is better to understand Thread lifecycle on this picture 在此处输入图片说明

Your working threads will be in Terminated state (die) after join returns.

From join() method code :

public final synchronized void join(long millis) throws InterruptedException {
    ...
    while (isAlive()) {
        wait(0);
    }
    ...
}

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