Java先发制人吗?

我已经看到了很多这个问题的答案,但我仍然不确定。

其中之一是“Java是先发制人”。 (JVM使用抢占式,基于优先级的调度算法(通常是循环算法)进行调度。

第二个是如果2个具有相同优先级的线程运行Java将不会抢占,并且一个线程可能会饿死。

所以现在我编写了一个程序来检查它,我创建了10个具有最小优先级的线程,然后是10个具有最高优先级的线程,结果是我在所有线程之间跳转 – 这意味着即使两个线程具有相同的线程,Java也是抢先的优先

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.util.logging.Level; import java.util.logging.Logger; /** * * @ */ public class JavaApplication1 { /** * @param args the command line arguments */ public static void main(String[] args) { for (int i=0;i<10;i++){ Thread t=new Thread(new Dog(i)); t.setPriority(Thread.MIN_PRIORITY); t.start(); } try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < 10; i++) { Thread g = new Thread(new Dog(i+10)); g.setPriority(Thread.MAX_PRIORITY); g.start(); } } } 

Ť

 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; /** * * @author Matan2t */ public class Dog implements Runnable{ public int _x=-1; public Dog(int x){ _x=x; } @Override public void run(){ while(true){ System.out.println("My Priority Is : " + _x); } } } 

我不认为这是指定的,正如两个引号中的任何一个所暗示的那样。 我能找到的只有 :

每个线程都有优先权。 具有较高优先级的线程优先于具有较低优先级的线程执行。 当在某个线程中运行的代码创建一个新的Thread对象时,新线程的优先级最初设置为等于创建线程的优先级。

除此之外,我相信这些机制是特定于平台和JVM的。 在我熟悉的平台上,JVM使用OS线程,因此依赖于OS调度程序。

也就是说,鉴于默认情况下所有应用程序线程都具有相同的优先级,如果这些线程无法相互抢占,则会非常不方便。