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();
}
}
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西