多线程:head first Thread.join()
不使用Thread.join() 测试线程
先上代码:
/**
* Created by Zero on 2017/8/23.
*/
public class TestJoin implements Runnable {
public static int a = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
a = a + 1;
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin j = new TestJoin();
Thread thread = new Thread(j);
thread.start();
System.out.println(a);
}
}
以上示例会输出5吗?可能性不大,有可能永远输出为0,之前在线程池原理的那篇就提到过,线程的启动和销毁都需要时间,此处因为thread还没启动好,或者正在为它分配资源准备运行,就已经执行完输出了。
怎样才能确保每次都能输出5呢?现在有请我们的主角join方法闪亮登场,代码如下:
/**
* Created by apple on 2017/8/23.
*/
public class TestJoin implements Runnable {
public static int a = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
a = a + 1;
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin j = new TestJoin();
Thread thread = new Thread(j);
thread.start();
/**
* 测试join方法的作用,与下面的threadAgain线程作对比。
*/
thread.join();
System.out.println(a);
a = 0;
Thread threadAgain = new Thread(j);
threadAgain.start();
System.out.println(a);
}
}
输出的结果将是5和0。
Thread.join()作用
Thread.join(),之前看资料的时候,有些人说可以理解成“将两个线程合并成一个线程”,我是觉得这样说是很不科学的,虽然这样通俗易懂,但这确实是两个不同的线程,只是在调用Thread.join()后,会先执行完Thread线程后再去执行当前线程,即上述的在主线程中执行到thread.join();后,先去执行thread,直到thread执行完后再去执行主线程。
测试Thread.join(long millis)
/**
* Created by apple on 2017/8/23.
*/
public class TestJoin implements Runnable {
public static int a = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
a = a + 1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin j = new TestJoin();
Thread thread = new Thread(j);
thread.start();
/**
* 测试join方法的作用
*/
thread.join(3000);
System.out.println("thread线程结果为:"+a);
a = 0;
Thread threadAgain = new Thread(j);
threadAgain.start();
System.out.println("threadAgain线程结果为:"+a);
}
}
输出:
thread线程结果为:3
threadAgain线程结果为: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.
*/
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;
}
}
}
源码爸爸说了,孩子,我给你millis这么长的时间,能不能完成任务那是你的事情了,能提前完成,咱就提前走下去,不能完成,过期不候,自己看着办吧。
默认情况下,Thread.join()即Thread.join(0),当为0的时候,那才叫真爱呢,线程会一直等下去,知道执行结束为止,才会继续朝下执行。
isAlive():用来测试线程是否处于活动状态,相当于 run 是否还在执行。
多线程:head first Thread.join()的更多相关文章
- 多线程进阶---Thread.join()/CountDownLatch.await() /CyclicBarrier.await()
Thread.join() CountDownLatch.await() CyclicBarrier.await() 三者都是用来控制程序的"流动" 可以让程序"堵塞&q ...
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
本篇我们将讨论以下知识点: 1.线程同步问题的产生 什么是线程同步问题,我们先来看一段卖票系统的代码,然后再分析这个问题: package com.zejian.test; /** * @author ...
- C#多线程详解(一) Thread.Join()的详解
bicabo C#多线程详解(一) Thread.Join()的详解 什么是进程?当一个程序开始运行时,它就是一个进程,进程包括运行中的程序和程序所使用到的内存和系统资源.而一个进程又是由多个线程 ...
- 多线程编程(一) - 关于C#中Thread.Join()
Thread.Join()在MSDN中的解释很模糊:Blocks the calling thread until a thread terminates 有两个主要问题:1.什么是the calli ...
- C#多线程Thread.Join()的详解
class TestThread { private static void FirstThreadFun() { ; i < ; i++) { Console.WriteLine(Thread ...
- 多线程--Thread.join方法
在Thread类的Api中,Join的作用是让当前线程等待目标线程结束之后才继续执行. thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程. 比如在线程B ...
- java 多线程 Thread.join子线程结束父线程再运行;join(long):等待超时毫秒数
Join的使用 目的:当子线程运行结束后,父线程才能再继续运行 /** * @ClassName ThreadJoinExample * @projectName: object1 * @author ...
- C#中Thread.Join()的理解
最近在项目中使用多线程,但是对多线程的一些用法和概念还有有些模棱两可,为了搞清楚查阅了一写资料,写下这篇日志加深理解吧. Thread.Join()在MSDN中的解释很模糊:Blocks the ca ...
- Java Thread.join的作用和原理
很多人对Thread.join的作用以及实现了解得很少,毕竟这个api我们很少使用.这篇文章仍然会结合使用及原理进行深度分析 内容导航 Thread.join的作用 Thread.join的实现原理 ...
随机推荐
- 自定义类似于Jquery UI Selectable 的Vue指令v-selectable
话不多说,先看效果. 其实就是一个可以按住鼠标进行一个区域内条目选择的功能,相信用过Jquery UI 的都知道这是selectable的功能,然而我们如果用Vue开发的话没有类似的插件,当然你仍然可 ...
- JQuery中的回调对象
JQuery中的回调对象 回调对象(Callbacks object)模块是JQuery中的一个很基础的模块,很多其他的模块(比如Deferred.Ajax等)都依赖于Callbacks模块的实现.本 ...
- javascript多种方法实现数组去重
先说说这个实例的要求:写一个方法实现数组的去重.(要求:执行方法,传递一个数组,返回去重后的新数组,原数组不变,实现过程中只能用一层循环,双层嵌套循环也可写,只做参考): 先给初学者解释一下什么叫数组 ...
- UI设计|PS软件操作应用——GIF动图
前 言 JRedu 在之前的分享中,跟大家主要讲解了PS软件工具的基本操作,对主要的图层.蒙版.通道和滤镜都有一些介绍,希望对大家有所帮助,在介绍这些工具时也提到过GIF,而在本次分享中就跟大家 ...
- testng-result中文乱码问题
背景 执行完用例查看报告,发现testng-result.xml文件中关于中文的都是乱码 解决方法 eclipse已设置了utf-8去编译,所以直接运行run as testng ,在console栏 ...
- 基于FPGA的中值滤波算法实现
在这一篇开篇之前,我需要解决一个问题,上一篇我们实现了基于FPGA的均值滤波算法的实现,最后的显示效果图上发现有一些黑白色的斑点,我以为是椒盐噪声,然后在做基于FPGA的中值滤波算法的实验时,我发现黑 ...
- 【Linux】用yum安装JDK(转)
1.查看yum库中都有哪些jdk版本(暂时只发现了openjdk) [root@localhost ~]# yum search java|grep jdk ldapjdk-javadoc.x86_6 ...
- Response.Write 、RegisterClientScriptBlock和RegisterStartupScript总结
Response.Write .RegisterClientScriptBlock和RegisterStartupScript总结 Page.ClientScript.RegisterStartupS ...
- log4j日志框架学习
初识Log4j: log4j有三个部分: 1.loggers 负责捕获日志信息. 2.appenders 负责输出信息到不同的目的地 ...
- iOS 微信支付流程详解
背景 自微信支付.支付宝支付入世以来,移动端的支付日渐火热.虚拟货币有取代实体货币的趋向(这句纯属扯淡,不用管),支付在app开发中是一项基本的功能,有必要去掌握.从难易程度上讲,不管是微信支付还是支 ...