什么 是线程优先级?
线程优先级是指优先级越高,越有可能先执行,但只是建议先执行,具体什么时候执行由系统决定。
设置线程优先级
- 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);
}
}