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

Thread.join()的用法

作者头像
小小明童鞋
发布2018-06-13 16:13:00
7530
发布2018-06-13 16:13:00
举报
文章被收录于专栏:java系列博客java系列博客

Thread.join()语句的含义:当前线程A等待thread线程终止之后才从thred.join()返回。

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

代码语言:javascript
复制
package cn.com.test;

import java.util.concurrent.TimeUnit;

public class Join {
	
	public static void main(String[] args) throws Exception {
		Thread previous = Thread.currentThread();
		for (int i = 0; i < 10; i++) {
			// 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
			Thread thread = new Thread(new Domino(previous), String.valueOf(i));
			thread.start();
			previous = thread;
		}
		TimeUnit.SECONDS.sleep(5);
		System.out.println(Thread.currentThread().getName() + " terminate.");
	}

	static class Domino implements Runnable {
		private Thread thread;

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

		public void run() {
			try {

				thread.join();

			} catch (InterruptedException e) {
				// TODO: handle exception
			}

			System.out
					.println(Thread.currentThread().getName() + " terminate.");
		}
	}
}

输出结果如下:

代码语言:javascript
复制
main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.

关于线程是怎么从join()中返回的没看懂,先码下来再说。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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