java中的线程优先级_Java中线程优先级的重要性?

在多线程应用程序中,每个线程都分配有一个优先级。线程调度程序根据线程的优先级将处理器分配给该线程,即,优先级最高的线程首先分配给处理器,依此类推。值为' 5'的线程的默认优先级。我们可以使用Thread类的getPriority()方法获得线程的优先级。

Thread类中为线程优先级定义的三个静态值

MAX_PRIORITY

这是最大线程优先级,值为10。

NORM_PRIORITY

这是默认的线程优先级,值为5。

MIN_PRIORITY

这是最小线程优先级,值为1。

语法public final int getPriority()

示例public class ThreadPriorityTest extends Thread {

public static void main(String[]args) {

ThreadPriorityTest thread1 = new ThreadPriorityTest();

ThreadPriorityTest thread2 = new ThreadPriorityTest();

ThreadPriorityTest thread3 = new ThreadPriorityTest();

System.out.println("Default thread priority of thread1: " + thread1.getPriority());

System.out.println("Default thread priority of thread2: " + thread2.getPriority());

System.out.println("Default thread priority of thread3: " + thread3.getPriority());

thread1.setPriority(8);

thread2.setPriority(3);

thread3.setPriority(6);

System.out.println("New thread priority of thread1: " + thread1.getPriority());

System.out.println("New thread priority of thread2: " + thread2.getPriority());

System.out.println("New thread priority of thread3: " + thread3.getPriority());

}

}

输出结果Default thread priority of thread1: 5

Default thread priority of thread2: 5

Default thread priority of thread3: 5

New thread priority of thread1: 8

New thread priority of thread2: 3

New thread priority of thread3: 6


版权声明:本文为weixin_32803887原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。