(1)join方法是可以中断的
(2)在线程joiner在另一个线程t上调用t.join(),线程joiner将被挂起,直到线程t结束(即t.isAlive()返回为false)才恢复

package thread.join2;

class Sleeper extends Thread{
private int duration;
public Sleeper(String name,int sleepTime) {
super(name);
duration=sleepTime;
start();
}
@Override
public void run() {
try {
sleep(duration);
} catch (InterruptedException e) {
System.out.println(currentThread()+" was interrupted. isInterrupted():"+isInterrupted());
return;
}
System.out.println(currentThread()+" was awakened");
}
} class Joiner extends Thread{
private Sleeper sleeper;
public Joiner(String name,Sleeper sleeper) {
super(name);
this.sleeper=sleeper;
start();
} @Override
public void run() {
try {
sleeper.join();
} catch (InterruptedException e) {
System.out.println(currentThread()+" Interrupted.");
}
System.out.println(currentThread()+" join completed.");
} } public class JoinTest { public static void main(String[] args) {
int sleepTime=1500;
Sleeper sleepy_sleeper=new Sleeper("sleepy_sleeper", sleepTime);
Sleeper grumpy_sleeper=new Sleeper("grumpy_sleeper", sleepTime); Joiner dopey_joiner=new Joiner("dopey_joiner", sleepy_sleeper);
Joiner doc_joiner=new Joiner("doc_joiner", grumpy_sleeper);
grumpy_sleeper.interrupt();
} }

Output:

Thread[grumpy_sleeper,5,main] was interrupted. isInterrupted():false
Thread[doc_joiner,5,main] join completed.
Thread[sleepy_sleeper,5,main] was awakened
Thread[dopey_joiner,5,main] join completed.

一、使用方式。

join是Thread类的一个方法,启动线程后直接调用,例如:

1
Thread t = new AThread(); t.start(); t.join();

二、为什么要用join()方法

在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需要用到子线程的处理结果,也就是主线程需要等待子线程执行完成之后再结束,这个时候就要用到join()方法了。

三、join方法的作用

在JDk的API里对于join()方法是:

join

public final void join() throws InterruptedException Waits for this thread to die. Throws: InterruptedException  - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

即join()的作用是:“等待该线程终止”,这里需要理解的就是该线程是指的主线程等待子线程的终止。也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。

四、用实例来理解

写一个简单的例子来看一下join()的用法:

1.AThread 类

  1. BThread类

  2. TestDemo 类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    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 < 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 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");
            }
        }
    }
    public class TestDemo {
        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!");
        }
    }

    打印结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    main start.    //主线程起动,因为调用了at.join(),要等到at结束了,此线程才能向下执行。
    [BThread] Thread start.
    [BThread] Thread loop at 0
    [BThread] Thread loop at 1
    [AThread] Thread start.    //线程at启动,因为调用bt.join(),等到bt结束了才向下执行。
    [BThread] Thread loop at 2
    [BThread] Thread loop at 3
    [BThread] Thread loop at 4
    [BThread] Thread end.
    [AThread] Thread end.    // 线程AThread在bt.join();阻塞处起动,向下继续执行的结果
    main end!      //线程AThread结束,此线程在at.join();阻塞处起动,向下继续执行的结果。

    修改一下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class TestDemo {
        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(); //在此处注释掉对join()的调用
            catch (Exception e) {
                System.out.println("Exception from main");
            }
            System.out.println(threadName + " end!");
        }
    }

    打印结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    main start.    // 主线程起动,因为Thread.sleep(2000),主线程没有马上结束;
     
    [BThread] Thread start.    //线程BThread起动
    [BThread] Thread loop at 0
    [BThread] Thread loop at 1
    main end!   // sleep两秒后主线程结束,AThread执行的bt.join();并不会影响到主线程。
    [AThread] Thread start.    //线程at起动,因为调用了bt.join(),等到bt结束了,此线程才向下执行。
    [BThread] Thread loop at 2
    [BThread] Thread loop at 3
    [BThread] Thread loop at 4
    [BThread] Thread end.    //线程BThread结束了
    [AThread] Thread end.    // 线程AThread在bt.join();阻塞处起动,向下继续执行的结果

    五、从源码看join()方法

    在AThread的run方法里,执行了bt.join();,进入看一下它的JDK源码:

    1
    2
    3
    public final void join() throws InterruptedException {
        join(0L);
    }

    然后进入join(0L)方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public final synchronized void join(long l)
        throws InterruptedException
    {
        long l1 = System.currentTimeMillis();
        long l2 = 0L;
        if(l < 0L)
            throw new IllegalArgumentException("timeout value is negative");
        if(l == 0L)
            for(; isAlive(); wait(0L));
        else
            do
            {
                if(!isAlive())
                    break;
                long l3 = l - l2;
                if(l3 <= 0L)
                    break;
                wait(l3);
                l2 = System.currentTimeMillis() - l1;
            while(true);
    }

    单纯从代码上看: * 如果线程被生成了,但还未被起动,isAlive()将返回false,调用它的join()方法是没有作用的。将直接继续向下执行。 * 在AThread类中的run方法中,bt.join()是判断bt的active状态,如果bt的isActive()方法返回false,在bt.join(),这一点就不用阻塞了,可以继续向下进行了。从源码里看,wait方法中有参数,也就是不用唤醒谁,只是不再执行wait,向下继续执行而已。 * 在join()方法中,对于isAlive()和wait()方法的作用对象是个比较让人困惑的问题:

    isAlive()方法的签名是:public final native boolean isAlive(),也就是说isAlive()是判断当前线程的状态,也就是bt的状态。

    wait()方法在jdk文档中的解释如下:

    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

    The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

    在这里,当前线程指的是at。

http://www.open-open.com/lib/view/open1371741636171.html

Java Thread.join()详解(转)的更多相关文章

  1. 【转】Java Thread.join()详解

    http://www.open-open.com/lib/view/open1371741636171.html 一.使用方式. join是Thread类的一个方法,启动线程后直接调用,例如: ? 1 ...

  2. Java Thread.join()详解--父线程等待子线程结束后再结束

    目录(?)[+] 阅读目录 一.使用方式. 二.为什么要用join()方法 三.join方法的作用 join 四.用实例来理解 打印结果: 打印结果: 五.从源码看join()方法   join是Th ...

  3. Java Thread.join()详解

    一.使用方式. 二.为什么要用join()方法 三.join方法的作用 join 四.用实例来理解 打印结果: 打印结果: 五.从源码看join()方法   一.使用方式. join是Thread类的 ...

  4. Java Thread.yield详解

    这是Java中的一种线程让步方法,让Java中的线程从执行状态变成就绪状态,然后处理器再从就绪队列中挑选线程进行执行(优先级大的,被挑选的概率较大),这种转换也不确定,让或者不让都是取决与处理器,线程 ...

  5. Thread.join详解

    /** * 如果某个线程在另一个线程t上调用t.join:那么此线程将被挂起,直到目标t线程的结束才恢复即t.isAlive返回为假 * * @date:2018年6月27日 * @author:zh ...

  6. [译]Java Thread join示例与详解

    Java Thread join示例与详解 Java Thread join方法用来暂停当前线程直到join操作上的线程结束.java中有三个重载的join方法: public final void ...

  7. Java基础-进程与线程之Thread类详解

    Java基础-进程与线程之Thread类详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.进程与线程的区别 简而言之:一个程序运行后至少有一个进程,一个进程中可以包含多个线程 ...

  8. java.lang.Thread类详解

    java.lang.Thread类详解 一.前言 位于java.lang包下的Thread类是非常重要的线程类,它实现了Runnable接口,今天我们来学习一下Thread类,在学习Thread类之前 ...

  9. Java线程创建形式 Thread构造详解 多线程中篇(五)

    Thread作为线程的抽象,Thread的实例用于描述线程,对线程的操纵,就是对Thread实例对象的管理与控制. 创建一个线程这个问题,也就转换为如何构造一个正确的Thread对象. 构造方法列表 ...

随机推荐

  1. 【AC大牛陈鸿的ACM总结贴】【ID AekdyCoin】人家当初也一样是菜鸟

    acm总结帖_By AekdyCoin 各路大牛都在中国大陆的5个赛区结束以后纷纷发出了退役帖,总结帖,或功德圆满,或死不瞑目,而这也许又会造就明年的各种"炸尸"风波.为了考虑在发 ...

  2. WSGI详解

    WSGI接口 了解了HTTP协议和HTML文档,我们其实就明白了一个Web应用的本质就是: 浏览器发送一个HTTP请求: 服务器收到请求,生成一个HTML文档: 服务器把HTML文档作为HTTP响应的 ...

  3. hdoj 1286 找新朋友 【数论之欧拉函数】

    找新朋友 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submi ...

  4. 不包含SDK头文件, 补全API定义

    /// @file main.cpp /// @brief 不包含SDK头文件, 补全API定义 #ifdef __cplusplus extern "C" { #endif /* ...

  5. UIGestureRecognizer在多层视图中的触发问题

    在一个superview中,添加了一个subview.tap一下superview,将subview隐藏起来. 在视图superview添加一个UITapGestureRecognizer对象,在UI ...

  6. Spring MVC Controller与jquery ajax请求处理json

    在用 spring mvc 写应用的时候发现jquery传递的[json数组对象]参数后台接收不到,多订单的处理,ajax请求: "}]}]} $.ajax({ url : url, typ ...

  7. 部署Spring Boot应用

    在开发Spring Boot应用的过程中,Spring Boot直接执行public static void main()函数并启动一个内嵌的应用服务器(取决于类路径上的以来是Tomcat还是jett ...

  8. Problem K: Yikes -- Bikes!

    http://acm.upc.edu.cn/problem.php?id=2780 昨天做的题,没过……!!!伤心……题意:给你n个单位,n-1组关系,让你单位换算……解题思路:Floyd算法自己听别 ...

  9. 使用 Nginx 创建服务器的负载均衡

    译序         Nginx 的负载均衡配置看上去很简单.以下是 Nginx 官方给的一个简单的负载均衡的例子: http {   upstream myproject {     server ...

  10. vc 按钮自绘

    按钮自绘,将按钮区域分成三部分,左边.右边.中间都由贴图绘制,可用于手动进度条按钮,或者左右选择项按钮 cpp代码部分: // LRSkinButton.cpp : implementation fi ...