线程是否根据各自的优先级编号工作?

Do threads work with respect to their respective priority number?

为什么编译器会打印 2 a 然后打印 2 b 或反之亦然,当 Thread a 优先启动时?线程 b 不应该等待线程 a 完成才能启动吗?有人可以解释一下它是如何工作的吗?

public class Test1 extends Thread{
    static int x = 0;
    String name;

    Test1(String n) {
      name = n;
    }

    public void increment() {
        x = x+1;
        System.out.println(x + " " + name);
    }

    public void run() {
        this.increment();
    }
}

public class Main {
    public static void main(String args[]) {
        Test1 a = new Test1("a");
        Test1 b = new Test1("b");
        a.setPriority(3);
        b.setPriority(2);
        a.start();
        b.start();
    }
}

Shouldn't thread b wait for thread a to finish in order to start?

没有。优先级不会阻塞线程执行。它只告诉 JVM 执行线程"in preference to threads with lower priority"。这确实意味着等待。

既然你的代码如此简单,就没有什么可等待的了。两个线程中的任何一个都是 运行.

给出优先级不是编译器的工作。它是 OS 调度程序,用于调度并为线程提供 CPU 时间(称为量程)。

调度程序会根据 CPU 的可用数量进一步尝试一次 运行 尽可能多的线程。在当今的多核系统中,可用的内核往往不止一个。

如果您想让一个线程等待另一个线程,请使用某种同步机制。

Why would the compiler print 2 a and then 2 b?

开奖。 "Priority" 在不同的操作系统上意味着不同的东西,但总的来说,它始终是 OS 如何决定哪个线程进入 运行 以及当没有足够的 CPU 可用时哪个线程必须等待的一部分运行 他们同时。如果您的计算机在启动该程序时有两个或更多空闲 CPU,那么每个人都会达到 运行。在这种情况下,优先级并不重要,这只是一场比赛,看谁先到达 println(...) 呼叫。

您的示例中的 a 线程有一个优势,因为程序直到 a.start() 方法 returns 之后才调用 b.start(),但是这个优势有多大实际上是取决于OS线程调度算法的细节。 a 线程可能会取得巨大的领先优势(例如,它实际上在 b 甚至开始之前就完成了),或者它可能是一个近乎微不足道的领先优势。