为什么两个最低和最高优先级的线程仍然交错?

时间:2017-03-27 10:32:10

标签: java multithreading

考虑使用以下课程:

public class RunnableDemo implements Runnable {
       private Thread t;
       private String threadName;

       RunnableDemo( String name) {
          threadName = name;
          System.out.println("Creating thread " +  threadName );
       }

       @Override
       public void run() {
          System.out.println("Running thread" +  threadName );
          try {
             for(int i = 4; i > 0; i--) {
                System.out.println("Thread " + threadName + ", iteration: " + i);
                // Let the thread sleep for a while.
                Thread.sleep(50);
             }
          } catch (InterruptedException e) {
             System.out.println("Thread " + threadName + " interrupted.");
          }
          System.out.println(threadName + " exiting.");
       }

       public void Fire (int priority) {
          System.out.println("Starting thread " +  threadName );
          if (t == null) {
             t = new Thread (this, threadName);
             t.setPriority(priority);
             t.start ();
          }
       }
}

另一个测试它的课程:

public class TestThread {

    public TestThread() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
          RunnableDemo R1 = new RunnableDemo( "RunnableDemo-One");      
          RunnableDemo R2 = new RunnableDemo( "RunnableDemo-Two");

          R1.Fire(Thread.MAX_PRIORITY);
          R2.Fire(Thread.MIN_PRIORITY);
    }

}

运行时此代码段的输出为:

Creating thread RunnableDemo-One
Creating thread RunnableDemo-Two
Starting thread RunnableDemo-One
Starting thread RunnableDemo-Two
Running threadRunnableDemo-One
Thread RunnableDemo-One, iteration: 4
Running threadRunnableDemo-Two
Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-Two, iteration: 1
Thread RunnableDemo-One, iteration: 1
RunnableDemo-Two exiting.
RunnableDemo-One exiting.

换句话说,尽管一个线程具有MAX_PRIORITY而另一个线程具有MIN_PRIORITY,但系统仍然在它们之间进行交错,就像它们具有相同的优先级一样。 为什么

以不同的方式表达同一个问题:是否有方案或代码修改,其中程序的输出将是:

Thread RunnableDemo-One, iteration: 4
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-One, iteration: 1

Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-Two, iteration: 1

即,仍然将它们保持为独立且独立的线程?

1 个答案:

答案 0 :(得分:2)

JVM将线程呈现给操作系统,这里优先级基于JVM调度算法再次发挥作用,但它最终决定的操作系统因此,它自己的算法会尝试尽可能多地使用CPU核心在争用资源的多个线程之间循环。

但是,如果有一个用例,你希望在第二个之前完成一个线程,你可以考虑使用join()。