线程优先级与调度 05

 

  • 优先级与调度:1. java中线程是有优先级的。

                                   2. Thread类有三个优先级的静态常量:Tread.MIN_PRIORITY(优先级最小)

                                                                                                 Tread.MAX_PRIORITY(优先级最高)

                                                                                                 NORM_PRIORITY(表示缺省优先级,默认值为5)

  • 优先级的操作:1. 获得线程的优先级:int get Priority();

    2. 改变线程的优先级:对象.setPriority(Thread.优先级)

  • 调度:1. 目前计算机多数是单个CPU以上某种顺序执行的多个线程为线程的调度。

                      2. java中线程调度采用抢先式调用方法。

  • 抢先式调度模式:1. 低优先级线程被高优先等级线程强占运行,每个线程都有优先级,可用setPriority方法

                                     改变。每个优先级有一个等待池。

2. 由于优先级低的线程只有等优先级高的线程运行完毕或者优先级高的线程进入阻塞状态

    才有机会运行,为了让优先级低的线程也有机会运行,通常会不时让优先级高的线程进

    入睡眠或者等待状态让出CPU的控制权。

注意:线程优先级仍无法保障线程的执行次序,只是获取CPU概率较大。

package src;
class SimpleThread extends Thread
{
String name;
SimpleThread(String threadname)
{
name=threadname;
}
public void run()
{
for (int i=0;i<3;i++)
System.out.println(name+"第"+i+"次运行"+",优先级为:"+getPriority());
}
}
class Setprio
{
public static void main(String args [])
{
Thread t1=new SimpleThread("t1");
t1.setPriority(Thread.MIN_PRIORITY);
t1.start();
Thread t2=new SimpleThread("t2");
t2.setPriority(Thread.MAX_PRIORITY);
t2.start();
Thread t3=new SimpleThread("t3");
t3.start();
Thread t4=new SimpleThread("t4");
t4.start();
}
}
posted @ 2022-07-24 20:50  zjw_rp  阅读(78)  评论(0)    收藏  举报