多线程: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的实现原理 ...
随机推荐
- 音频软件开发中的debug方法和工具
本文系作者原创.如转载,请注明出处. 谢谢! 音频软件开发同其他软件开发一样,都需要去调试.音频软件调试同其他软件调试方法有相同的地方,也有不同的地方,同时调试时还需要借助一些专门的工具,有了这些方法 ...
- java protected修饰符理解
Protected类型可以在本包和子类中访问的含义.在本包中访问,顾名思义,可以在定义类的包中的任何地方申请一个包含protected修饰符的域和方法的类的对象,并通过这个对象访问被protected ...
- MySQL 账户管理
一.当前日期.当前用户.当前数据库版本 mysql> select curdate(),version(),database(),user(); +------------+---------- ...
- Redis在电商中的实际应用-Java
示例代码用Jedis编写. 1. 各种计数,商品维度计数和用户维度计数 说起电商,肯定离不开商品,而附带商品有各种计数(喜欢数,评论数,鉴定数,浏览数,etc),Redis的命令都是原子性的,你可以轻 ...
- 转每天一个linux命令(4):mkdir命令
linux mkdir 命令用来创建指定的名称的目录,要求创建目录的用户在当前目录中具有写权限,并且指定的目录名不能是当前目录中已有的目录. 1.命令格式: mkdir [选项] 目录... 2.命令 ...
- linux下FTP服务器搭建教程1
你买了个主机就像是买了块地皮,搭建FTP就像是盖房子,我在地皮上建房子,然后创建的用户就像是钥匙,我给谁钥匙(权限),谁就可以到我家去玩,去放东西,拿东西. 虽然我们买不起现实的房子,但是我们可以买互 ...
- 用openssl库RSA加密解密
#include <stdio.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include < ...
- [2017-08-25]100行CSharp代码利用dynamic写个DSL(特定领域语言)
最近看<CLR via C#(第4版)> 读到第五章末尾dynamic基元类型时,看了下作者的一个利用dynamic动态调用string类型的Contains方法(静态方法)的实现,突然发 ...
- Flink从Kafka 0.8中读取多个Topic时的问题
Flink提供了FlinkKafkaConsumer08,使用Kafka的High-level接口,从Kafka中读取指定Topic的数据,如果要从多个Topic读取数据,可以如下操作: 1.appl ...
- IDEA集成SSH Session
1,在菜单栏选择Tools -> Start SSH Session 2,在SSH Session表单中输入: 3,在IDEA下方会弹出Terminal控制台,直接敲命令即可. ------- ...