栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

Java Thread.join()具有什么功能呢?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Thread.join()具有什么功能呢?

转自:

Java Thread.join()具有什么功能呢?

下文笔者讲述java中Thread.join()的功能简介说明,如下所示:

Thread.join()方法的功能:
  用于等待进程
 如:主线程创建子线程
      当子线程运行时间非常长时,主线程通常会在子线程之前结束,
	   当主线程需等待子线程的处理结果时,此时我们需要使用join()方法 

Thread.join()方法的语法

//无参数的join()等价于join(0),作用是一直等待该线程死亡
join() throws InterruptedException;  
//最多等待该线程死亡millis毫秒
join(long millis, int nanos) throws InterruptedException;  
//最多等待该线程死亡millis毫秒加nanos纳秒
join(long millis, int nanos) throws InterruptedException ; 

 package com.java265.other;

public class Test3 {
	public static void main(String[] args) {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		BThread bt = new BThread();
		AThread at = new AThread(bt);
		try {
			bt.start();
			Thread.sleep(2000);
			at.start();
			at.join();
		} catch (Exception e) {
			System.out.println("Exception from main");
		}
		System.out.println(threadName + " end!");
	}
}

class BThread extends Thread {
	public BThread() {
		super("[BThread] Thread");
	};

	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		try {
			for (int i = 0; i < 6; i++) {
				System.out.println(threadName + " loop at " + i);
				Thread.sleep(1000);
			}
			System.out.println(threadName + " end.");
		} catch (Exception e) {
			System.out.println("Exception from " + threadName + ".run");
		}
	}
}

class AThread extends Thread {
	BThread bt;

	public AThread(BThread bt) {
		super("[AThread] Thread");
		this.bt = bt;
	}

	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		try {
			bt.join();
			System.out.println(threadName + " end.");
		} catch (Exception e) {
			System.out.println("Exception from " + threadName + ".run");
		}
	}
}
------运行以上代码,将输出以下信息------
main start.
[BThread] Thread start.
[BThread] Thread loop at 0
[BThread] Thread loop at 1
[BThread] Thread loop at 2
[AThread] Thread start.
[BThread] Thread loop at 3
[BThread] Thread loop at 4
[BThread] Thread loop at 5
[BThread] Thread end.
[AThread] Thread end.
main end!
join()方法注意事项:
  1. 当一个线程s在另一个线程t上调用t.join()
       此线程s将被挂起,直到目标线程t结束才恢复(此时t.isAlive()返回为假)
      也可以在调用join()时带上一个超时参数(单位可以是毫秒,或者毫秒和纳秒)
      当目标线程在这段时间内还没有结束的话,join()方法总能返回
       对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。
 2. 当线程生成后,但还未被起动,isAlive()将返回false,调用它的join()方法是没有作用的
      将直接继续向下执行 
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1040539.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号