M
M
mitaichik2016-03-27 21:25:11
Java
mitaichik, 2016-03-27 21:25:11

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();
        }

Is it spelled correctly? A phrase from a Java book is confusing, something like "Join joins a thread to the parent thread, and the parent thread will not be completed until all joined threads are completed"
On the one hand, like join waits for the thread to complete, on the other hand, judging by In the words of the book, it doesn't wait for the thread to complete, and moves on, just causing the main thread to not terminate until the joined threads are done.
Tell me how it actually works?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-03-27
@mitaichik

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 question

Ask a Question

731 491 924 answers to any question