java - Java线程中的优先级

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

}

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

最佳答案

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

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

关于java - Java线程中的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205859/

相关文章:

c++ - 如何提高多线程效率?

java - 为什么一个线程阻塞了我的 JavaFX UI 线程?

java - 启动/停止线程 Java

java - 在云被阻止的环境中使用 azure cosmos db 模拟器进行开发

java - Intellij 封装 JavaFx 应用程序

java - 加载 .so 库时出现问题

java - Jar 文件有类,但我仍然得到 java.lang.ClassNotFoundException : org. apache.kafka.clients.consumer.ConsumerRecord

java - 如何测试线程之间值的可见性

c++ - Python PyGILState_{Ensure/Release} 在从 Python 代码返回到 C++ 时导致段错误

java - 是否建议将Arraylist转换为Reactor的flux来处理数据?