线程的优先级:
1.MAX_PRIORITY :10
MIN_PRIORITY :1
NORM_PRIORITY :5 -->默认优先级
2.如何获取和设置当前线程的优先级:
getPriority():获取线程的优先级
setPriority(int p):设置线程的优先级
说明:高优先级的线程要抢占低优先级线程的cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
public class ThreadMethodTest {
public static void main(String[] args) {
Thread.currentThread().setName("主线程");
Thread.currentThread().setPriority(MIN_PRIORITY);
HelloThread h1 = new HelloThread();
h1.setName("线程一");
h1.setPriority(MAX_PRIORITY);
h1.start();
for (int i = 0; i < 1000; i++) {
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() +":"+Thread.currentThread().getPriority() + ":" + i);
}
}
}
}
class HelloThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
if(i % 2 == 0){
System.out.println(getName() +"+" + getPriority() + ":" + i);
}
}
}
}
运行结果:
从而印证了线程优先级的高低是概率问题,并不是一定会执行完,低优先级的线程才会执行。就如转幸运大转盘,就算三分之二都是中奖,仍然有可能好几次都不中奖。
Java小白,刚开始学习,不喜勿喷,欢迎讨论。