个人随笔
目录
Thread.join()的使用
2020-04-07 23:17:15

如果一个线程A执行了thread.join()语句,其含义是:当前线程A等待thread线程终止之后才从thrad.join()返回。线程thread除了提供join()方法之外,还提供了join(long millis)和join(long millis,int nanos)两个具备超时特性的方法。这两个超时方法表示,如果线程thread在给定的超时时间里没有终止,那么将会从该方法中返回。

如下例子,创建了10个线程,编号0~9,每个线程调用前一个线程的join()方法,也就是线程0结束了,线程1才能从join()方法中返回,而线程0需要等待main线程结束。

  1. public class JoinTest {
  2. public static void main(String[] args) throws InterruptedException {
  3. Thread previous = Thread.currentThread();
  4. for (int i = 0; i <10; i++) {
  5. //每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
  6. Thread thread = new Thread(new Demo(previous),String.valueOf(i));
  7. thread.start();
  8. previous=thread;
  9. }
  10. //主线程也就是第一个父线程休眠5秒
  11. TimeUnit.SECONDS.sleep(5);
  12. System.out.println(Thread.currentThread().getName()+" terminate.");
  13. }
  14. static class Demo implements Runnable{
  15. private Thread thread;
  16. public Demo(Thread thread) {
  17. this.thread = thread;
  18. }
  19. @Override
  20. public void run() {
  21. try {
  22. //thread线程终止之后才会继续执行
  23. thread.join();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. System.out.println(Thread.currentThread().getName()+" terminate.");
  28. }
  29. }
  30. }

运行程序结果如下

  1. main terminate.
  2. 0 terminate.
  3. 1 terminate.
  4. 2 terminate.
  5. 3 terminate.
  6. 4 terminate.
  7. 5 terminate.
  8. 6 terminate.
  9. 7 terminate.
  10. 8 terminate.
  11. 9 terminate.

结果跟预想的一致。

 583

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2