Mat*_*uti 7 java multithreading preemptive thread-priority
我已经看到了很多这个问题的答案,但我仍然不确定.
其中之一是"Java是先发制人".(JVM使用抢占式,基于优先级的调度算法(通常是循环算法)进行调度.
第二个是如果两个具有相同优先级的线程运行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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ť
/*
* 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
NPE*_*NPE 10
我不认为这是指定的,正如两个引号中的任何一个所暗示的那样.我能找到的只有:
每个线程都有优先权.具有较高优先级的线程优先于具有较低优先级的线程执行.当在某个线程中运行的代码创建一个新的Thread对象时,新线程的优先级最初设置为等于创建线程的优先级.
除此之外,我相信这些机制是特定于平台和JVM的.在我熟悉的平台上,JVM使用OS线程,因此依赖于OS调度程序.
这就是说,因为在默认情况下所有应用程序线程具有相同的优先级,它会如果这些线程没有能力抢占彼此是令人难以置信的不便.
归档时间: |
|
查看次数: |
5784 次 |
最近记录: |