当前位置:   article > 正文

Android中主线程等待子线程方法实现_android 主线程等待子线程完成

android 主线程等待子线程完成

日常开发中,我们会遇到多个子线程并发请求,最终合并返回结果到主线程的情况,下面介绍两种实现方法.

方法一:使用join()

  1. public void Test() {
  2. System.out.println(System.currentTimeMillis() + ":开始执行");
  3. final Thread thread1 = new Thread(new Runnable() {
  4. @Override
  5. public void run() {
  6. try {
  7. Thread.sleep(5000);
  8. System.out.println("thread1:执行完了");
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. }
  13. });
  14. thread1.start();
  15. final Thread thread2 = new Thread(new Runnable() {
  16. @Override
  17. public void run() {
  18. try {
  19. Thread.sleep(1000);
  20. System.out.println("thread2:执行完了");
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. });
  26. thread2.start();
  27. try {
  28. thread1.join();
  29. thread2.join();
  30. System.out.println(System.currentTimeMillis() + ":子线程都执行完了" );
  31. } catch (InterruptedException e) {
  32. e.printStackTrace();
  33. }
  34. }

方法二:使用CountDownLatch

  1. private CountDownLatch countDownLatch = new CountDownLatch(2);
  2. public void Test() {
  3. System.out.println(System.currentTimeMillis() + ":开始执行");
  4. Thread thread1 = new Thread(new Runnable() {
  5. @Override
  6. public void run() {
  7. try {
  8. Thread.sleep(5000);
  9. countDownLatch.countDown();
  10. System.out.println("thread1:执行完了");
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. });
  16. thread1.start();
  17. Thread thread2 = new Thread(new Runnable() {
  18. @Override
  19. public void run() {
  20. try {
  21. Thread.sleep(1000);
  22. System.out.println("thread2:执行完了");
  23. countDownLatch.countDown();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. });
  29. thread2.start();
  30. try {
  31. countDownLatch.await();
  32. System.out.println(System.currentTimeMillis() + ":子线程执行完了");
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. }

以上两种方法比较容易理解且实现简单,希望能帮到你.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/465185
推荐阅读
相关标签
  

闽ICP备14008679号