背景
多线程的线程优先级。
实现
Thread的setPriority方法可设置线程的优先级。
代码
注:
- setPriority()方法要先于start()方法执行,需要先设置线程的优先级才会生效;
- 优先级高仅表示线程获得CPU调度的权重大,并不代表着一定会先于优先级低的线程执行。
package com.langjialing;
public class ThreadPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
MyPriorith myPriorith = new MyPriorith();
Thread t0 = new Thread(myPriorith);
Thread t1 = new Thread(myPriorith);
Thread t2 = new Thread(myPriorith);
Thread t3 = new Thread(myPriorith);
Thread t4 = new Thread(myPriorith);
t0.setPriority(Thread.MAX_PRIORITY); //Thread.MAX_PRIORITY,线程的最大优先级,默认为10
t1.setPriority(Thread.MIN_PRIORITY); //Thread.MIN_PRIORITY,线程的最小优先级,默认为1
t2.setPriority(3);
t3.setPriority(5);
t4.setPriority(7);
t0.start();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyPriorith implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
效果
总结
Thread的setPriority方法可设置线程的优先级。但优先级仅表示获得CPU调度的权重,并不一定是优先级的高就一定会先执行。