JAVA-线程优先级setPriority
1. 说明
线程分为1-10级,10级最高,优先级的高低不代表线程优先执行,需要看CPU的情况,一般情况下优先级高的先执行,程序先执行主方法,在执行线程。
2. 代码实现
public class TestPriorty {
public static void main(String[] args) {
//主线程
System.out.println(Thread.currentThread().getName()+"线程正在进行中"+Thread.currentThread().getPriority());
Mypriorty mypriorty=new Mypriorty();
//子线程
Thread thread1=new Thread(mypriorty,"小黄");
Thread thread2=new Thread(mypriorty,"小红");
Thread thread3=new Thread(mypriorty,"小李");
Thread thread4=new Thread(mypriorty,"小明");
Thread thread5=new Thread(mypriorty,"小张");
//设置优先级/启动线程
thread1.setPriority(1);
thread1.start();
thread2.setPriority(5);
thread2.start();
thread3.setPriority(10);
thread3.start();
thread4.setPriority(4);
thread4.start();
thread5.setPriority(Thread.MAX_PRIORITY);//最高级
thread5.start();
}
}
class Mypriorty implements Runnable{
@Override
public void run() {
//打印线程名称和优先级
try { System.out.println(Thread.currentThread().getName()+"线程正在进行中"+Thread.currentThread().getPriority());
} catch (Exception e) {
e.printStackTrace();
}
catch (Error d) {
d.printStackTrace();
}
}
}
3. 运行结果