執行緒優先順序(執行緒具有繼承性、setPriority、getPriority)
阿新 • • 發佈:2018-11-12
什麼 是執行緒優先順序?
執行緒優先順序是指優先順序越高,越有可能先執行,但只是建議先執行,具體什麼時候執行由系統決定。
設定執行緒優先順序
- public final void setPriority(int newPriority) ;
取得執行緒優先順序
- public final int getPriority( );
在Thread類中定義了三種靜態成員變數:
- public final static int MIN_PRIORITY = 1;
- public final static int NORM_PRIORITY = 5;
- public final static int MAX_PRIORITY = 10;
也就是執行緒優先順序的取值範圍是1-10;
我們知道主方法是一個JVM程序的主執行緒,那主執行緒的優先順序是多少呢?
public class Prio
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getPriority()); //主執行緒優先順序為5
}
}
主執行緒的優先順序只是一個普通優先順序—>5。
有了優先順序可以設定執行緒優先順序,當多個執行緒併發執行時,將某個執行緒優先順序設高,建議cpu先排程這個執行緒,但具體什麼時候排程由系統決定。
程式碼如下:
class Mythraed3 implements Runnable
{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
public class Prio
{
public static void main(String[] args)
{
Mythraed3 thread=new Mythraed3();
Thread thread1=new Thread(thread,"執行緒1");
Thread thread2=new Thread(thread,"執行緒2");
Thread thread3=new Thread(thread,"執行緒3");
thread1.setPriority(2);
thread2.setPriority(6);
thread3.setPriority(Thread.MAX_PRIORITY); //將執行緒3優先順序設定最高
thread1.start();
thread2.start();
thread3.start();
}
}
執行緒具有繼承性
執行緒是有繼承關係的,比如當A執行緒中啟動B執行緒,那麼B和A的優先順序將是一樣的。
////執行緒具有繼承性
class Mythraed3 implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName()+"優先順序為"+Thread.currentThread().getPriority());
Thread thread=new Thread(new Mythraed4(),"執行緒2");
thread.start(); //線上程1裡啟動執行緒2,執行緒2優先順序和執行緒1優先順序一樣
}
}
class Mythraed4 implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName()+"優先順序為"+Thread.currentThread().getPriority());
}
}
public class Prio
{
public static void main(String[] args)
{
Mythraed3 thread=new Mythraed3();
Thread thread1=new Thread(thread,"執行緒1");
thread1.start();
thread1.setPriority(3);
}
}