W
W
WTFAYD2017-08-19 17:23:57
Java
WTFAYD, 2017-08-19 17:23:57

How does the compiler run tasks in a for loop at the same time?

Hello!
Let's say there is a code:

ExecutorService exec = Executors.newThreadCachedPool();
for(int i = 0; i < 10; i++)
    exec.execute(new SomeRunnable());

How does the compiler run all 10 tasks at the same time, if, as I understand it, the for loop is a sequential iteration from the 0th to the 9th element; therefore, there must be some delay between threads starting (especially between the first and the last). How is it even possible to write multi-threaded code within a code if the code itself is a kind of sequential algorithm of commands? Got confused a little.
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
roswell, 2017-08-19
@WTFAYD

It does not start the compiler, but the runtime, and the ExecutorService starts each process in its own asynchronous thread. There is a delay between iterations in the loop, but it can be taken almost equal to zero. By the way, still Executors.newCachedThreadPool() .

A
Alexander Movchan, 2017-08-19
@Alexander1705

First, the compiler does not run anything, but only compiles the program.
Secondly, the tasks do not run simultaneously, but sequentially, as you expected. But since tasks are started on a new thread, the program does not wait for them to complete before starting the next one.
There is a delay between launches, but it is insignificant.

G
GavriKos, 2017-08-19
@GavriKos

1) The compiler does not run anything from your code at all.
2) Well, how. I created a thread, the thread works separately - the cycle went further. The delay is stupid for creating a thread, but not for its execution logic.
Yes. Within a single thread, this is true. But within a few, no.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question