Answer the question
In order to leave comments, you need to log in
How do threads work in Java?
Misters, help a lammer to understand flows!
Task: n threads are created in a loop and run. After the loop, you need to wait until they are all executed.
I got this code:
List<Thread> threads = new ArrayList<>();
for(int i = 0; i < 10; i++){
Thread thread = new Thread(new Calculate());
thread.start();
threads.add(thread);
}
for(Thread thread : threads){
thread.join();
}
Answer the question
In order to leave comments, you need to log in
join() blocks the parent thread until the thread on which join() is called ends. Actually, it is precisely because the parent does not go further after the call to join() that it will not complete earlier.
To illustrate, try inserting an infinite loop in your Calculate, and after thread.join(); - System. out.println("joined");
On the topic of the code - everything is ok, except that InterruptedException is not taken into account, which can throw join
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question