0%

16.4.5 改变线程优先级

16.4.5 改变线程优先级

线程优先级的作用

每个线程执行时都具有一定的优先级,优先级高的线程获得较多的执行机会,而优先级低的线程则获得较少的执行机会

默认与父类优先级相同

每个线程默认的优先级都与创建它的父线程的优先级相同,在默认情况下,main线程具有普通优先级,所以由main线程创建的子线程也具有普通优先级。

如何设置,查询优先级

Thread类提供了setPriority(int newPriority)getPriority()方法来设置和返回指定线程的优先级,其中setPriority()方法的参数可以是一个整数,范围是1-10之间,也可以使用Thread类提供的三个静态常量来设置优先级,如下所示:

  • MAX_PRIORITY,其值是10
  • NORM_PRIORITY,其值是5
  • MIN_PRIORITY,其值是1

程序示例

下面程序使用了setPriority()方法来改变主线程的优先级,并使用该方法改变了两个线程的优先级,从而可以看到高优先级的线程将会获得更多的执行机会

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class PriorityTest extends Thread
{
// 定义一个有参数的构造器,用于创建线程时指定name
public PriorityTest(String name)
{
super(name);
}
public void run()
{
for (int i = 0 ; i < 50 ; i++ )
{
System.out.println(getName() + ",其优先级是:"
+ getPriority() + ",循环变量的值为:" + i);
}
}
public static void main(String[] args)
{
// 改变主线程的优先级
Thread.currentThread().setPriority(6);
for (int i = 0 ; i < 30 ; i++ )
{
if (i == 10)
{
PriorityTest low = new PriorityTest("低级");
low.start();
System.out.println("创建之初的优先级:"
+ low.getPriority());
// 设置该线程为最低优先级
low.setPriority(Thread.MIN_PRIORITY);
}
if (i == 20)
{
PriorityTest high = new PriorityTest("高级");
high.start();
System.out.println("创建之初的优先级:"
+ high.getPriority());
// 设置该线程为最高优先级
high.setPriority(Thread.MAX_PRIORITY);
}
}
}
}

优先级级别需要操作系统支持

值得指出的是,虽然Java提供了10个优先级级别,但这些优先级级别需要操作系统的支持。遗憾的是,不同操作系统上的优先级并不相同,而且也不能很好地和Java的10个优先级对应,例如Windows 2000仅提供了7个优先级。因此应该尽量避免直接为线程指定优先级,而应该使用MAX_PRIORITYNORM_PRIORITYMIN PRIORITY三个静态常量来设置优先级,这样才可以保证程序具有最好的可移植性。

原文链接: 16.4.5 改变线程优先级