Priorities in Java Threads

I do not understand the output of this code:

package examplepriorities;

class Counter extends Thread {

    public Counter(String name) {
        super(name);
    }

    @Override
    public void run() {
        int count = 0;
        while (count <= 1000) {
            System.out.println(this.getName() + ": " + count++);
        }
    }
}

public class ExamplePriorities {

    public static void main(String[] args) {
        Counter thread1 = new Counter("thread 1");
        thread1.setPriority(10);

        Counter thread2 = new Counter("thread 2");
        thread2.setPriority(1);

        thread1.start();
        thread2.start();
    }

}

At the output, you can see messages printed from thread 1 from 0 to 1000, and when these threads finish, the second thread starts to print messages. I know that the first thread has a higher priority level, but since there are (I suppose) free cores in the processor, why don't both threads do their work at the same time?

+4
source share
2 answers

This is similar to how the OS scheduler decided to schedule them. If I run my code, I get:

thread 1: 0
thread 1: 1
thread 1: 2
thread 1: 3
thread 1: 4
thread 1: 5
thread 1: 6
thread 1: 7
thread 1: 8
thread 1: 9
thread 1: 10
thread 1: 11
thread 1: 12
thread 1: 13
thread 1: 14
thread 1: 15
thread 1: 16
thread 1: 17
thread 1: 18
thread 1: 19
thread 1: 20
thread 1: 21
thread 1: 22
thread 1: 23
thread 1: 24
thread 1: 25
thread 1: 26
thread 1: 27
thread 1: 28
thread 1: 29
thread 1: 30
thread 1: 31
thread 1: 32
thread 1: 33
thread 1: 34
thread 1: 35
thread 1: 36
thread 1: 37
thread 1: 38
thread 1: 39
thread 2: 0
thread 2: 1
thread 2: 2
thread 2: 3
thread 2: 4
thread 1: 40
thread 1: 41
thread 1: 42
thread 1: 43
thread 1: 44
thread 2: 5
thread 2: 6
thread 2: 7
thread 2: 8
thread 2: 9
thread 2: 10
thread 1: 45
thread 1: 46
thread 1: 47
thread 1: 48
thread 2: 11
thread 1: 49
thread 1: 50
thread 1: 51
thread 1: 52
thread 1: 53
thread 2: 12
thread 2: 13
thread 2: 14
thread 2: 15
thread 2: 16
thread 2: 17
thread 2: 18
thread 1: 54
thread 2: 19
thread 2: 20
thread 2: 21
thread 2: 22
thread 1: 55
thread 1: 56
thread 2: 23
thread 1: 57
thread 2: 24
thread 2: 25
thread 2: 26
thread 1: 58
thread 1: 59
thread 1: 60
thread 2: 27
thread 2: 28
thread 2: 29
thread 1: 61
thread 2: 30
thread 1: 62
thread 2: 31
thread 1: 63
+2
source

If you increase the amount of work that each thread should perform by setting the number of iterations to 100_000000, for example, the threads will be executed in parallel.

thread 1: 1447678
thread 2: 127862
thread 2: 127863
thread 2: 127864
thread 2: 127865
thread 2: 127866

, .

/ , , 1000 .

, , , .

+2

Source: https://habr.com/ru/post/1689010/


All Articles