java中join方法的理解與說明詳解
前言:
java 中的 join() 方法在多線程中會涉及到,這個方法最初理解起來可能有點抽象,用一兩次大概就懂了。簡單說就是當前線程等待調用join方法的線程結束才能繼續(xù)往下執(zhí)行。
1. 舉個例子
如下,
MyRunnable 類是實現(xiàn) Runnable 接口的多線程類,其run() 方法是一個計算,計算值存儲在 result 字段,獲取計算結果就必須等線程執(zhí)行完之后調用 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());
}
}
獲取計算結果需要持續(xù)判斷線程 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函數(shù))會等待thread_1 結束后才繼續(xù)執(zhí)行下面的代碼。
2. jion() 方法源碼解析
其實 join() 方法內(nèi)部的實現(xiàn)跟上面例子中的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 方法如果不傳參數(shù)會默認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方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

