日常開發中,我們會遇到多個子執行緒并發請求,最終合并回傳結果到主執行緒的情況,下面介紹兩種實作方法.
方法一:使用join()
public void Test() {
System.out.println(System.currentTimeMillis() + ":開始執行");
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
System.out.println("thread1:執行完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
final Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println("thread2:執行完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
System.out.println(System.currentTimeMillis() + ":子執行緒都執行完了" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
方法二:使用CountDownLatch
private CountDownLatch countDownLatch = new CountDownLatch(2);
public void Test() {
System.out.println(System.currentTimeMillis() + ":開始執行");
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
countDownLatch.countDown();
System.out.println("thread1:執行完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println("thread2:執行完了");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread2.start();
try {
countDownLatch.await();
System.out.println(System.currentTimeMillis() + ":子執行緒執行完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
以上兩種方法比較容易理解且實作簡單,希望能幫到你.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/290907.html
標籤:其他
