有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

调度线程时的java JVM公平性

在调度线程执行时,JVM是否公平

对于下面的代码段,是否可以只执行“代码A”,而忽略B

public static void main(String args[]) {

    new Thread() {
      public void run() {
        for (;;) { /* code A */ }
      }
    }.start();

    new Thread() {
      public void run() {
        for (;;) { /* code B */ }
      }
    }.start();

}

这个问题更多的是一个理论上的问题——让我们假设两个线程都不会被阻塞,或者以其他方式鼓励调度器切换上下文


共 (1) 个答案

  1. # 1 楼答案

    Are there any assumptions on how fair JVM is when it comes to scheduling threads for execution?

    没有

    For the below snippet, is it possible to have "code A" executed only, with B being ignored?

    理论上是的

    实际上:

    • 如果有一个(可用的)内核,我希望操作系统级的线程调度程序对线程进行时间切片,以便每个线程在日志项中获得大约50%的可用时间

    • 如果有多个(可用)内核,我希望这两个线程并行运行


    请注意,JLS或JVM规范都没有提到线程调度或公平性。对于Thread的javadoc也是如此

    据我所知,唯一提到公平性的Java API是ReentrantLockAPI(javadoc),其中有一个构造函数参数,用于创建具有公平性策略的锁。这意味着调度程序支持在锁上等待时间最长的线程。但就连这一点也值得注意:

    "Note however, that fairness of locks does not guarantee fairness of thread scheduling."