【Java多线程系列随笔一】浅析 Java Thread.join()
一、在研究join的用法之前,先明确两件事情。
1、join方法定义在Thread类中,则调用者必须是一个线程,
例如:
Thread t = new CustomThread(); //这里一般是自定义的线程类 t.start();//线程起动 t.join();//此处会抛出InterruptedException异常
2、上面的两行代码也是在一个线程里面执行的。
以上出现了两个线程,一个是我们自定义的线程类,我们实现了run方法,做一些我们需要的工作;另外一个线程,生成我们自定义线程类的对象,然后执行。
customThread.start();
customThread.join();
在这种情况下,两个线程的关系是一个线程由另外一个线程生成并起动,所以我们暂且认为第一个线程叫做“子线程”,另外一个线程叫做“主线程”。
二、为什么要用join()方法
主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算(这里可以借鉴下线程的作用),当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。
三、join方法的作用
在网上看到有人说“将两个线程合并”。这样解释我觉得理解起来还更麻烦。不如就借鉴下API里的说法: “等待该线程终止。”
解释一下,是主线程(我在“一”里已经命名过了)等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。(Waits for this thread to die.)
四、用实例来理解
写一个简单的例子来看一下join()的用法,一共三个类:
1.CustomThread 类
2. CustomThread1类
3. JoinTestDemo 类,main方法所在的类。
代码一、
class CustomThread1 extends Thread {
public CustomThread1() {
super("[CustomThread1] Thread");
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
try {
for (int i = 0; i < 5; 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 CustomThread extends Thread {
CustomThread1 t1;
public CustomThread(CustomThread1 t1){
super("[CustomThread] Thread");
this.t1 = t1;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start!");
try {
t1.join();
System.out.println(threadName + " end!");
} catch (Exception e) {
System.out.println("Exception from " + threadName + " run!");
}
}
}
public class JoinTest {
public static void main(String[] args) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
CustomThread1 t1 = new CustomThread1();
CustomThread t = new CustomThread(t1);
try {
t1.start();
Thread.sleep(1000L);
t.start();
t.join(); //在代码2里,注释掉此行
} catch (InterruptedException e) {
System.out.println("Exception from main");
}
System.out.println(threadName + " end!");
}
}
打印结果:
main start.
[CustomThread1] Thread start.
[CustomThread1] Thread loop at 0
[CustomThread] Thread start!
[CustomThread1] Thread loop at 1
[CustomThread1] Thread loop at 2
[CustomThread1] Thread loop at 3
[CustomThread1] Thread loop at 4
[CustomThread1] Thread end.
[CustomThread] Thread end!
main end!
代码二、
package com.concurrent.test.join;
class CustomThread1 extends Thread {
public CustomThread1() {
super("[CustomThread1] Thread");
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
try {
for (int i = 0; i < 5; 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 CustomThread extends Thread {
CustomThread1 t1;
public CustomThread(CustomThread1 t1){
super("[CustomThread] Thread");
this.t1 = t1;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start!");
try {
t1.join();
System.out.println(threadName + " end!");
} catch (Exception e) {
System.out.println("Exception from " + threadName + " run!");
}
}
}
public class JoinTest {
public static void main(String[] args) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " start.");
CustomThread1 t1 = new CustomThread1();
CustomThread t = new CustomThread(t1);
try {
t1.start();
Thread.sleep(1000L);
t.start();
//t.join();
} catch (InterruptedException e) {
System.out.println("Exception from main");
}
System.out.println(threadName + " end!");
}
}
打印结果:
main start.
[CustomThread1] Thread start.
[CustomThread1] Thread loop at 0
main end!
[CustomThread1] Thread loop at 1
[CustomThread] Thread start!
[CustomThread1] Thread loop at 2
[CustomThread1] Thread loop at 3
[CustomThread1] Thread loop at 4
[CustomThread1] Thread end.
[CustomThread] Thread end!
五、从源码看join()方法
JDK源码:
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
进入join(0) 方法,查看源码:
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*
* millis 主线程等待时间
*/
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0; if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
} if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
如果线程被生成了,但还未被起动,调用它的join()方法是没有作用的。
【Java多线程系列随笔一】浅析 Java Thread.join()的更多相关文章
- Java多线程系列--“基础篇”03之 Thread中start()和run()的区别
概要 Thread类包含start()和run()方法,它们的区别是什么?本章将对此作出解答.本章内容包括:start() 和 run()的区别说明start() 和 run()的区别示例start( ...
- 【Java多线程系列随笔二】BlockingQueue
前言: 在新增的Concurrent包中,BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便 ...
- Java多线程系列目录(共43篇)
最近,在研究Java多线程的内容目录,将其内容逐步整理并发布. (一) 基础篇 01. Java多线程系列--“基础篇”01之 基本概念 02. Java多线程系列--“基础篇”02之 常用的实现多线 ...
- Java多线程系列--“基础篇”11之 生产消费者问题
概要 本章,会对“生产/消费者问题”进行讨论.涉及到的内容包括:1. 生产/消费者模型2. 生产/消费者实现 转载请注明出处:http://www.cnblogs.com/skywang12345/p ...
- Java多线程系列--“基础篇”04之 synchronized关键字
概要 本章,会对synchronized关键字进行介绍.涉及到的内容包括:1. synchronized原理2. synchronized基本规则3. synchronized方法 和 synchro ...
- Java多线程系列--“基础篇”05之 线程等待与唤醒
概要 本章,会对线程等待/唤醒方法进行介绍.涉及到的内容包括:1. wait(), notify(), notifyAll()等方法介绍2. wait()和notify()3. wait(long t ...
- Java多线程系列--“基础篇”06之 线程让步
概要 本章,会对Thread中的线程让步方法yield()进行介绍.涉及到的内容包括:1. yield()介绍2. yield()示例3. yield() 与 wait()的比较 转载请注明出处:ht ...
- Java多线程系列--“基础篇”07之 线程休眠
概要 本章,会对Thread中sleep()方法进行介绍.涉及到的内容包括:1. sleep()介绍2. sleep()示例3. sleep() 与 wait()的比较 转载请注明出处:http:// ...
- Java多线程系列--“基础篇”08之 join()
概要 本章,会对Thread中join()方法进行介绍.涉及到的内容包括:1. join()介绍2. join()源码分析(基于JDK1.7.0_40)3. join()示例 转载请注明出处:http ...
随机推荐
- crontab定时执行datax
记录下使用crontab,datax定时同步数据遇到的问题. 1.开始使用如下配置,死活不执行.网上说crontab环境便利的问题,设置了也没反应. [root@hxjk_test_mysql_red ...
- Webx.0-Web2.0:Web2.0
ylbtech-Webx.0-Web2.0:Web2.0 Web2.0 是相对于Web1.0 的新的时代.指的是一个利用Web的平台,由用户主导而生成的内容互联网产品模式,为了区别传统由网站雇员主导生 ...
- C++——智能指针
动态内存管理:new-delete——很难正确释放内存——智能指针 使用场景: 1.程序不知道自己要使用多少对象 2.程序不知道自己所需对象的准确类型 3.程序需要在多个对象之间共享数据 4.坚持只使 ...
- LightOJ 1030 Discovering Gold (概率/期望DP)
题目链接:LightOJ - 1030 Description You are in a cave, a long cave! The cave can be represented by a \(1 ...
- [已解决]报错: twisted 18.7.0 requires PyHamcrest>=1.9.0
1.下载对应的Twisted,下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted 2.通过Anaconda3的Anaconda Promp ...
- Java Socket NIO示例总结
Java NIO是非阻塞IO的实现,基于事件驱动,非常适用于服务器需要维持大量连接,但是数据交换量不大的情况,例如一些即时通信的服务等等,它主要有三个部分组成: Channels Buffers Se ...
- ios打包,通过Xcode生成ipa文件
ios打包,通过Xcode生成ipa文件 干货文章 ·2018-03-21 19:03:47 打开ios项目目录,配置证书 将运行设备选择,如下图 选择:Product -> Scheme -& ...
- wdcp后台登陆访问失败处理方法
用putty或xsheel链接 进入之后输入命令 service wdcp restart 之后显示ok就成功了
- maven管理多模块
创建parent项目: 1.打开IDEA,注意这里不要勾选模板,用模板创建过maven项目的小伙伴都知道模板创建项目非常慢,所以这里不要选模板,需要的文件夹我们后面自己来创建就可以了.所以这个页面直接 ...
- Oracle 环境部署 以及数据库创建 ,用户新建和权限分配
1.右键我的电脑--->属性--->高级系统设置 2.环境变量---->新建 总共配置三个变量 (1)变量名 ORACLE_HOME 变量值 G:\app\TH\product\11 ...