Let’s say I’ve got this very simple code:
for(int i = 0; i < 10; i++) {
thread = new Thread(this);
thread.start();
}
However, in this code, the thread apparently starts 10 times at once and it doesn’t wait before the previous one is finished. How do you check if the thread is finished before letting the thread start again?
Before answering your question, I strongly encourage you to look into
ExecutorServicessuch as for instance theThreadPoolExecutor.Now to answer your question:
If you want to wait for the previous thread to finish, before you start the next, you add
thread.join()in between:If you want to kick off 10 threads, let them do their work, and then continue, you
joinon them after the loop: