W
W
WTFAYD2017-08-13 15:45:48
Java
WTFAYD, 2017-08-13 15:45:48

How is the order of text output determined in a multithreaded program?

Hello!
I'm currently learning multithreading in Java and I have a small question.
Let's say we have a program like this:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Task implements Runnable {
    private int countdown = 5;
    @Override
    public void run() {
        while (countdown-- > 0)
            System.out.println(Thread.currentThread().getName() + "- (" + countdown + ")");
    }
}

public class Program {
    public static void main(String[] args) {
        ExecutorService exc = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            exc.execute(new Task());
        }
        exc.shutdown();
    }
}

And the output looks like this:
pool-1-thread-1- (4)
pool-1-thread-1- (3)
pool-1-thread-1- (2)
pool-1-thread-1- (1)
pool-1-thread-1- (0)
pool-1-thread-2- (4)
pool-1-thread-2- (3)
pool-1-thread-2- (2)
pool-1-thread-2- (1)
pool-1-thread-2- (0)
pool-1-thread-3- (4)
pool-1-thread-3- (3)
pool-1-thread-3- (2)
pool-1-thread-3- (1)
pool-1-thread-3- (0)
pool-1-thread-5- (4)
pool-1-thread-5- (3)
pool-1-thread-5- (2)
pool-1-thread-5- (1)
pool-1-thread-5- (0)
pool-1-thread-4- (4)
pool-1-thread-4- (3)
pool-1-thread-4- (2)
pool-1-thread-4- (1)
pool-1-thread-4- (0)

As I correctly understood, all 5 created threads perform 5 of these tasks in parallel, but how is the output determined and carried out? This, it turns out, depends on how the scheduler switches between processes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cr2ed, 2017-08-13
@WTFAYD

This is "Chinese random". The same program will output data in a different order each time it is run.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question