1. 經常使用方法java
static void yield() | 當前線程讓出處理器(離開Running狀態),使當前線程進入Runnable狀態等待 |
static void sleep(times) | 使當前線程從Running放棄處理器進入Block狀態,休眠times毫秒,再返回到Runnable。編程 若是其餘線程打斷當前線程的Block(sleep),就會發生InterruptedException。ide |
int getPriority() | 獲取線程的優先級 |
void setPriority(int newPriority) | 修改線程的優先級spa 優先級越高的線程,不必定先執行,但該線程獲取到時間片的機會,會更多一些線程 |
void join() | 等待該線程終止 |
void join(long millis) | 等待參數指定的毫秒數 |
boolean isDaemon() | 用於判斷是否爲守護線程 |
void setDeamon(boolean on) | 用於設置線程爲守護線程 |
2.代碼實例blog
<1>ThreadSleepTest.java繼承
<2> ThreadPriorityTest.java接口
<3> ThreadDaemonTest.javaget
3. 案例題目it
編程建立兩個線程,線程一:打印 1 - 100 之間的全部奇數,線程二: 打印 1 - 100 之間的全部偶數。
在main方法,啓動上述兩個線程,同時執行。主線程:等待兩個線程終止。
方式一(實現繼承的方式)
1 public class SubThread1 extends Thread { 2 @Override 3 public void run() { 4 // 打印1 ~ 100之間的全部奇數 5 for (int i = 1; i <= 100; i += 2) { 6 System.out.println("子線程一中: i = " + i); 7 } 8 } 9 } 10 11 12 13 public class SubThread2 extends Thread { 14 @Override 15 public void run() { 16 // 打印1 ~ 100之間的全部偶數 17 for (int i = 2; i <= 100; i += 2) { 18 System.out.println("------子線程二中: i = " + i); 19 } 20 } 21 } 22 23 24 public class SubThreadTest { 25 26 public static void main(String[] args) { 27 28 SubThread1 st1 = new SubThread1(); 29 SubThread2 st2 = new SubThread2(); 30 31 st1.start(); 32 st2.start(); 33 34 System.out.println("主線程開始等待..."); 35 try { 36 st1.join(); 37 st2.join(); 38 } catch (InterruptedException e) { 39 e.printStackTrace(); 40 } 41 System.out.println("主線程等待結束!"); 42 } 43 }
方式二(實現接口的方式)
1 class SubRunnable1 implements Runnable { 2 @Override 3 public void run(){ 4 // 打印1 ~ 100之間的全部奇數 5 for (int i = 1; i <= 100; i += 2) { 6 System.out.println("子線程一中: i = " + i); 7 } 8 } 9 } 10 11 class SubRunnable2 implements Runnable { 12 @Override 13 public void run() { 14 // 打印1 ~ 100之間的全部偶數 15 for (int i = 2; i <= 100; i += 2) { 16 System.out.println("------子線程二中: i = " + i); 17 } 18 } 19 } 20 21 class SubRunnableTest { 22 23 main(){ 24 SubRunnable1 sr1 = new SubRunnable1(); 25 SubRunnable2 sr2 = new SubRunnable2(); 26 27 Thread t1 = new Thread(sr1); 28 Thread t2 = new Thread(sr2); 29 30 t1.start(); 31 t2.start(); 32 33 print("主線程開始等待..."); 34 try{ 35 t1.join(); 36 t2.join(); 37 }catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 print("主線程等待結束!"); 41 42 } 43 }