前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java-并发-12.Thread.join()

Java-并发-12.Thread.join()

作者头像
悠扬前奏
发布2019-05-28 13:20:19
3170
发布2019-05-28 13:20:19
举报
  • 线程A执行thread.join(),表示A等待thread线程终止之后才从thread.join()返回
  • join(long millis)和join(long millis, int nanos)使其具有超时特性 代码示例:
代码语言:javascript
复制
import java.util.concurrent.TimeUnit;

/**
 * 创建10个线程,每个线程等待前一个线程的join()方法,0号线程等待main结束
 *
 * @author pengjunzhe
 */
public class Join {
    public static void main(String[] args) throws InterruptedException {
        Thread previous = Thread.currentThread();
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Domino(previous), String.valueOf(i));
            thread.start();
            previous = thread;
        }
        TimeUnit.SECONDS.sleep(3);
        System.out.println(Thread.currentThread().getName() + " terminate.");
    }

    static class Domino implements Runnable {
        private Thread thread;

        public Domino(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            try {
                thread.join();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " terminate.");
        }
    }
}

输出结果:

代码语言:javascript
复制
main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.05.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档