Java所有的线程在运行前都会保持在就绪状态,哪个线程的优先级高,哪个线程就有可能会先执行。
Java程序中有最高、中等、最低3种优先级,使用setPriority方法可以设置一个线程的优先级。
示例1:演示3种不同优先级的线程执行结果
public class TaskPriority implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "运行,i=" + i);
}
}
}
// 测试类
public class TaskPriorityTest {
public static void main(String[] args) {
Thread ta = new Thread(new TaskPriority(),"线程A");
Thread tb = new Thread(new TaskPriority(),"线程B");
Thread tc = new Thread(new TaskPriority(),"线程C");
ta.setPriority(Thread.MAX_PRIORITY); //设置A线程的优先级为最高
tb.setPriority(Thread.NORM_PRIORITY); //设置B线程的优先级为中等
tc.setPriority(Thread.MIN_PRIORITY); //设置C线程的优先级为最低
ta.start();
tb.start();
tc.start();
}
}
程序运行结果:
线程A运行,i=1
线程B运行,i=1
线程C运行,i=1
线程A运行,i=2
线程B运行,i=2
线程C运行,i=2
线程A运行,i=3
线程B运行,i=3
线程C运行,i=3
再次运行结果:
线程C运行,i=1
线程B运行,i=1
线程A运行,i=1
线程B运行,i=2
线程C运行,i=2
线程A运行,i=2
线程C运行,i=3
线程B运行,i=3
线程A运行,i=3
通过以上的程序运行结果可以看到,虽然线程可以设置优先级来决定哪个线程先运行,实际上哪个线程先执行是由CPU的调度决定的,并不是高优先级的线程一定会先执行。
示例2:获取主方法的优先级
使用getPriority方法可以获取一个线程的优先级。
public class GetPriorityTest {
public static void main(String[] args) {
System.out.println("主方法的优先级是:" + Thread.currentThread().getPriority());
}
}
程序运行结果:
主方法的优先级是:5
以上程序说明,主方法main线程的优先级常量是5,从上面的表格中可以看出,5代表中等优先级。因此说主线程的优先级是中等级别,一般情况下,线程默认的优先级就是中等级别。