java基礎-java執行緒如何設定優先順序
阿新 • • 發佈:2021-08-12
java執行緒如何設定優先順序
1.繼承Thread類重寫run方法
2.建立執行緒的實現類物件
3.threadDemo1.getPriority() 獲取執行緒的優先順序
4.threadDemo1.setPriority(10)設定執行緒的優先順序,數越高表示獲取CPU時間片的機率高,並不是每次數越大的都能優先獲取
5.建立並開始新執行緒
public class ThreadDemo extends Thread { //1)重寫run方法 @Override public void run() { for (int i = 1;i < 20;i++){ System.out.println(getName()+":"+i); } } public static void main(String[] args) { // 2)建立執行緒的實現類物件 ThreadDemo threadDemo1 = new ThreadDemo(); ThreadDemo threadDemo2 = new ThreadDemo(); ThreadDemo threadDemo3 = new ThreadDemo(); threadDemo1.setName("執行緒1"); threadDemo2.setName("執行緒2"); //3)獲取優先順序 System.out.println(threadDemo1.getPriority()); System.out.println(threadDemo2.getPriority()); System.out.println(threadDemo3.getPriority()); //4)設定優先順序 threadDemo2.setPriority(6); threadDemo1.setPriority(10); //5)建立並開始新執行緒 threadDemo1.start(); threadDemo2.start(); System.out.println(Thread.currentThread().getName()); } }