java线程中的优先级

时间:2017-11-09 15:37:47

标签: java multithreading

我不明白这段代码的输出:

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

}

在输出中,您可以看到从0到1000的线程1打印的消息,当这些线程完成其工作时,第二个线程开始打印消息。 我知道第一个线程具有更高的优先级,但是因为(假设)处理器中存在可用内核,为什么两个线程不能同时完成它们的工作呢?

2 个答案:

答案 0 :(得分:2)

这似乎是您的操作系统调度程序决定安排它们的方式。如果我运行你的代码,我会得到:

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

答案 1 :(得分:2)

如果增加每个线程应该做的工作量,例如通过将迭代次数设置为100_000000,线程将并行执行。

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

从输出中可以看出,在一个线程完成之前,线程两个已经安排好了。

最小优先级线程只是与来自其他应用程序/操作系统的线程竞争CPU资源,并且由于它具有最低优先级,因此在执行1000次迭代之前不会进行调度。

它按预期工作,第二个线程具有最低优先级,因此可以获得适当的少量CPU时间。