日常开发中,我们会遇到多个子线程并发请求,最终合并返回结果到主线程的情况,下面介绍两种实现方法.
方法一:使用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();
}
}
以上两种方法比较容易理解且实现简单,希望能帮到你.
|