主要方法:设置优先级public final void setPriority(int newPriority)
、取得优先级public final int getPriority()
public class TestThread3 {
public void code1(){
//1.主线程的优先级,中等优先级5
// System.out.println("主线程的优先级"+Thread.currentThread().getPriority());
//2.在主线程中创建一个线程,未指定优先级 lamda表达式
Thread threadA =new Thread(()->{
System.out.println(Thread.currentThread().getName()
+"优先级:"+Thread.currentThread()
.getPriority());
},"Thread-A");
threadA.start();
threadA.setPriority(6);
}
public static void main(String[] args) {
Runnable runnable=new PriorityRunnable();
Thread threadA =new Thread(runnable,"Thread-A");
threadA.setPriority(Thread.MAX_PRIORITY);//10
Thread threadB =new Thread(runnable,"Thread-B");
threadB.setPriority(Thread.MIN_PRIORITY);//5
Thread threadC =new Thread(runnable,"Thread-C");
threadC.setPriority(Thread.NORM_PRIORITY);//1
threadA.start();
threadB.start();
threadC.start();
}
}
class PriorityRunnable implements Runnable{
@Override
public void run() {
Thread t=Thread .currentThread();
System.out.println(t.getName()+"优先级"+t.getPriority());
}
}
线程是有继承关系的,比如当A线程中启动B线程,那么B和A的优先级将是一样的
public static void main(String[] args) {
//本来main优先级是5
System.out.println(Thread.currentThread().getName() + "," + Thread.currentThread().getPriority());
//main中启动A,设置优先级为10,则它的子和孙也是10
Thread thread = new Thread(new A(), "子线程A");
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
class A implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "," + Thread.currentThread().getPriority());
//A中启动B
new Thread(new B()).start();
}
}
class B implements Runnable {
@Override
public void run() {
System.out.println("孙子的优先级:" + Thread.currentThread().getPriority());
}
main,5
子线程A,10
孙子的优先级:10