1. 程式人生 > 程式設計 >java中join方法的理解與說明詳解

java中join方法的理解與說明詳解

前言:

java 中的 join() 方法在多執行緒中會涉及到,這個方法最初理解起來可能有點抽象,用一兩次大概就懂了。簡單說就是當前執行緒等待呼叫join方法的執行緒結束才能繼續往下執行。

1. 舉個例子

如下,

MyRunnable 類是實現 Runnable 介面的多執行緒類,其run() 方法是一個計算,計算值儲存在 result 欄位,獲取計算結果就必須等執行緒執行完之後呼叫 getResult() 獲取

public class MyRunnable implements Runnable {
 private int num;
 private String threadName;
 private long result;
 
 public MyRunnable(int num,String threadName) {
  this.threadName = threadName;
  this.num = num;
 }
 
 public void run() {
  for (int i = 0; i < num; i++) {
   result += i;
  }
 }
 
 
 public long getResult() {
  return result;
 }
}
 
public class NormalTest {
 public static void main(String[] args) {
 
  normal();
 
 }
 
 private static void normal() {
  MyRunnable myRunnable_1 = new MyRunnable(1000,"runnable_1");
 
  Thread thread_1 = new Thread(myRunnable_1);
  thread_1.start();
 
  do {
   System.out.println("--------------------------------------------------");
   System.out.println("thread status: " + thread_1.isAlive() + ",result: " + myRunnable_1.getResult());
  } while (thread_1.isAlive());
 }
}

獲取計算結果需要持續判斷執行緒 thread_1 是否結束才能最終獲取,輸出如下:

--------------------------------------------------
thread status: true,result: 0
--------------------------------------------------
thread status: true,result: 11026
--------------------------------------------------
thread status: false,result: 499500

而使用join()方法可以省去判斷的麻煩,如下

 
public class JoinTest {
 public static void main(String[] args) {
 
  join();
 
 }
 
 
 private static void join() {
 
  MyRunnable myRunnable_1 = new MyRunnable(1000,"runnable_1");
 
  Thread thread_1 = new Thread(myRunnable_1);
  thread_1.start();
 
  try {
   thread_1.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 
  System.out.println("thread status: " + thread_1.isAlive() + ",result: " + myRunnable_1.getResult());
 
 }
}

輸出如下:

thread status: false,result: 499500

呼叫join方法以後當前執行緒(在這裡就是main函式)會等待thread_1 結束後才繼續執行下面的程式碼。

2. jion() 方法原始碼解析

其實 join() 方法內部的實現跟上面例子中的normal()方法很類似,也是使用執行緒的 isAlive() 方法來判斷執行緒是否結束,核心原始碼如下:

 public final synchronized void join(long millis)
 throws InterruptedException {
  long base = System.currentTimeMillis();
  long now = 0;
 
  if (millis < 0) {
   throw new IllegalArgumentException("timeout value is negative");
  }
 
  if (millis == 0) {    // join 方法如果不傳引數會預設millis 為 0
   while (isAlive()) {
    wait(0);
   }
  } else {
   while (isAlive()) {
    long delay = millis - now;
    if (delay <= 0) {
     break;
    }
    wait(delay);
    now = System.currentTimeMillis() - base;
   }
  }
 }

當然上述還涉及 Object 類的 wait() 方法,感興趣可以查一下,這裡可以簡單的理解就是一個等待多少時間。

總結

到此這篇關於java中join方法的理解與說明的文章就介紹到這了,更多相關java中join方法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!