【发布时间】:2013-01-27 08:54:34
【问题描述】:
我已经看到了很多关于这个问题的答案,但我仍然不确定。
其中之一是“Java 是抢占式的”。 (JVM 使用抢占式、基于优先级的调度算法(通常是循环算法)进行调度。
第二个是如果 2 个具有相同优先级的线程运行 Java 将不会抢占,一个线程可能会饿死。
所以现在我写了一个程序来检查一下,我创建了 10 个最低优先级的线程 其次是 10 个具有最高优先级的线程, 结果是我在所有线程之间跳转——这意味着 Java 是抢占式的 即使 2 个线程具有相同的优先级
/*
* 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();
}
}
}
t
/*
* 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);
}
}
}
【问题讨论】:
标签: java multithreading thread-priority preemptive