線程的優先級
//最小優先級
public final static int MIN_PRIORITY = 1;
//正常優先級
public final static int NORM_PRIORITY = 5;
//最大優先級
public final static int MAX_PRIORITY = 10;
優先級可以繼承,A線程啓動B線程,則B線程的優先級和A一樣
MyThread1類
public class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1 run priority=" + this.getPriority());
MyThread2 thread2 = new MyThread2();
thread2.start();
}
}
public class MyThread2 extends Thread{
@Override
public void run() {
System.out.println("MyThread2 run priority=" + this.getPriority());
}
}
public class Run {
public static void main(String[] args) {
System.out.println("main thread begin priority=" + Thread.currentThread().getPriority());
System.out.println("main thread end priority=" + Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.setPriority(6);
thread1.start();
}
}
運行結果
main thread begin priority=5
main thread end priority=5
MyThread1 run priority=6
MyThread2 run priority=6
修改下run類代碼
public class Run {
public static void main(String[] args) {
System.out.println("main thread begin priority=" + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(6);
System.out.println("main thread end priority=" + Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.start();
}
}
運行結果:
main thread begin priority=5
main thread end priority=6
MyThread1 run priority=6
MyThread2 run priority=6
//注:之前的run類中是thread.setPriority(6); 結果thread1和thread2中的優先級都是6
之後的run類中是Thread.currentThread().setPriority(6); 相當把Main線程的優先級置成6了,所有後面的優先級也就都是6