线程的优先级
- MAX_PRIORITY:10
- MIN_PRIORITY: 1
- NORM_PRIORITY :5 --> 默认优先级
涉及方法
- getPriority() :获取线程的优先级。
- setPriority( int new Priority): 设置线程的优先级。
- 设置优先级要在该线程开始之前设置。
下面一段代码中利用上述的两个方法进行了设置和获取优先级。其中 “thread” 线程优先级为 10 ,而“主线程” 的优先级为 1 但是在运行结果中,仍然有主线程比thread 先打印输出。所以高优先级只是概率会比低优先级会多一点,并不能说高优先级一定会比低优先级先运行。
package ThreadMethodTest;
class MyThread extends Thread{
public MyThread(String s) {
this.setName(s);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() );
}
}
}
public class ThreadTest {
public static void main(String[] args) {
MyThread thread = new MyThread("thread");
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
Thread.currentThread().setName("主线程");
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
for (int i = 0 ;i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() );
}
}
}
运行截图
其他
- 线程创建时继承父线程的优先级
- 低优先级只是获得调度的概率低,并非一定低在高优先级线程之后才会被调用。