多线程: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的实现原理 ...
随机推荐
- selenium的操作JS命令的接口JavascriptExecutor的介绍
nterface JavascriptExecutor 接口 JS执行器 public interface JavascriptExecutor 表示可以执行JavaScript的驱动程序,提供对机制 ...
- Android自定义控件系列之基础篇
一.概述 在android开发中很多UI控件往往需要进行定制以满足应用的需要或达到更加的效果,接下来就通过一个系列来介绍自定义控件,这里更多是通过一些案例逐步去学习,本系列有一些典型的应用,掌握好了大 ...
- 我读《通过Go来处理每分钟达百万的数据请求》
我读<通过Go来处理每分钟达百万的数据请求> 原文 原文作者为Malwarebytes公司的首席架构师Marcio Castilho http://marcio.io/2015/07/ha ...
- Node.js之使用Buffer类处理二进制数据
Node.js之使用Buffer类处理二进制数据 Buffer类可以在处理TCP流或文件流时处理二进制数据,该类用来创建一个专门存放二进制数据的缓存区. 1. 创建Buffer对象 1.1 直接创建: ...
- ASP.NET Core 运行原理解剖[1]:Hosting
ASP.NET Core 是新一代的 ASP.NET,第一次出现时代号为 ASP.NET vNext,后来命名为ASP.NET 5,随着它的完善与成熟,最终命名为 ASP.NET Core,表明它不是 ...
- JSON数据表示格式简介(JavaScript对象表示法)
[1] JSON简介 > JSON全称 JavaScript Object Notation > 类似于JS中对象的创建的方法 > JSON和XML一样,都是一种表 ...
- jaspersoft studio 的初级入门(一)
前言 最近的工作涉及到企业的报表生成功能,于是就想用此篇博客来记录我的学习历程.进入Jasperreport项目的官网发现有一个软件叫Jaspersoft studio的,它的版本也是6.3.1跟Ja ...
- python selenium报错整理
element not visible 没有加等待时间 元素没有被选定,很多时候是因为没有最大化窗口,网页窗口只显示一部分,所以找不到元素! <exception str() failed> ...
- 论林耐斯-Linux系统的重要性
Linux--LinNaiSi系统的重要性... ===================================================== 飞机的控制系统.银行的系统.手机的系统我们 ...
- BotVS开发基础—2.7 指标MACD
代码 def main(): while true: records = _C(exchange.GetRecords); # 获取K线数据 ,默认为策略界面设置的K线周期, _C 是一个容错的内置函 ...