join方法
方法介紹:(強制執行)
1、在那個方法中調用就會阻塞哪個線程,不會阻塞別的線程。
2、在B線程中調用A.join();就會強制A線程執行,直到A線程執行完畢,B線程纔有搶佔CPU的權利,這過程中A,B之外的線程不受影響,依然可以和A線程搶佔CPU使用權。
sleep方法
方法介紹:(休眠)
使當前正在執行的線程休眠millis秒,線程處於阻塞狀態。
yield方法
方法介紹:(暫停)
當前線程暫停一次,讓出CPU使用權,進入就緒狀態,如果沒有其他線程,本線程馬上恢復執行。
線程優先級
獲取線程優先級的幾個方法:
1、線程名.getPriority()——獲取線程優先級
2、線程名.setPriority()——設置線程優先級
3、MAX_PRIORITY——最大優先級(10)
3、MIN_PRIORITY——最小優先級(1)
4、NORM_PRIORITY——默認優先級(5)
代碼樣例
public class a_Priority {
public static void main(String[] args) {
System.out.println("最小優先級:"+Thread.MIN_PRIORITY);
System.out.println("默認優先級:"+Thread.NORM_PRIORITY);
System.out.println("最大優先級:"+Thread.MAX_PRIORITY);
Thread thread = Thread.currentThread();
System.out.println("主線程優先級:"+thread.getPriority());
//創建線程
MyThread myThread = new MyThread();
Thread thread2 = new Thread(myThread);
thread2.setPriority(2);
System.out.println("新創建的線程優先級:"+thread2.getPriority());
}
}
class MyThread implements Runnable{
@Override
public void run() {
// TODO 自動生成的方法存根
}
}