Java如何设置线程的优先级?
线程总是以某种优先级运行,通常表示为1到10之间的数字(尽管在某些情况下范围小于10)。线程获得一个默认优先级,即创建它的执行线程的优先级。
但是,您也可以通过在 Thread 实例上调用 setPriority ()方法来直接设置线程的优先级。关于线程优先级,需要记住的一件事是,永远不要依赖于线程优先级,因为线程调度优先级行为不能得到保证。
package org.nhooo.example.lang;public class ThreadPriority extends Thread {
private String threadName;
ThreadPriority(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
System.out.println("Running [" + threadName + "]");
for (int i = 1; i <= 10; i++) {
System.out.println("[" + threadName + "] => " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadPriority thread1 = new ThreadPriority("First");
ThreadPriority thread2 = new ThreadPriority("Second");
ThreadPriority thread3 = new ThreadPriority("Third");
ThreadPriority thread4 = new ThreadPriority("Fourth");
ThreadPriority thread5 = new ThreadPriority("Fifth");
// 将thread1设置为最低优先级= 1
thread1.setPriority(Thread.MIN_PRIORITY);
// 将thread2设置为优先级2
thread2.setPriority(2);
// 将thread3设置为普通优先级= 5
thread3.setPriority(Thread.NORM_PRIORITY);
// 将thread4设置为优先级8
thread4.setPriority(8);
// 将thread5设置为最大优先级= 10
thread5.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
以上是 Java如何设置线程的优先级? 的全部内容, 来源链接: utcz.com/z/315877.html