在多线程应用程序中,每个线程都被分配一个优先级。处理器根据线程的优先级(即最高优先级的线程先分配处理器,依此类推)由线程调度器分配给线程。线程的默认优先级为5。我们可以使用Thread类的getPriority()方法来获取线程的优先级。
在Thread类中,定义了三个静态值来表示线程的优先级:
这是最高的线程优先级,值为10。
这是默认的线程优先级,值为5。
这是最低的线程优先级,值为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.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread2: " + thread2.<strong>getPriority</strong>()); System.out.println("Default thread priority of thread3: " + thread3.<strong>getPriority</strong>()); thread1.setPriority(8); thread2.setPriority(3); thread3.setPriority(6); System.out.println("New thread priority of thread1: " + thread1.<strong>getPriority()</strong>); System.out.println("New thread priority of thread2: " + thread2.<strong>getPriority()</strong>); System.out.println("New thread priority of thread3: " + thread3.<strong>getPriority()</strong>); } }
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
以上是在Java中,线程优先级的重要性是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!