虽然关于讨论线程join()方法的博客已经非常极其特别多了,但是前几天我有一个困惑却没有能够得到详细解释,就是当系统中正在运行多个线程时,join()到底是暂停了哪些线程,大部分博客给的例子看起来都像是t.join()方法会使所有线程都暂停并等待t的执行完毕。当然,这也是因为我对多线程中的各种方法和同步的概念都理解的不是很透彻。通过看别人的分析和自己的实践之后终于想明白了,详细解释一下希望能帮助到和我有相同困惑的同学。

首先给出结论:t.join()方法只会使主线程(或者说调用t.join()的线程)进入等待池并等待t线程执行完毕后才会被唤醒。并不影响同一时刻处在运行状态的其他线程。

下面则是分析过程。

之前对于join()方法只是了解它能够使得t.join()中的t优先执行,当t执行完后才会执行其他线程。能够使得线程之间的并行执行变成串行执行。

package csdn;
public class testjoin {
 
 public static void main(string[] args) throws interruptedexception {
  // todo auto-generated method stub
  threadtest t1=new threadtest("a");
  threadtest t2=new threadtest("b");
  t1.start();
  t2.start();
 }
 
 
}
class threadtest extends thread {
 private string name;
 public threadtest(string name){
  this.name=name;
 }
 public void run(){
  for(int i=1;i<=5;i++){
    system.out.println(name+"-"+i);
  }  
 }
}

运行结果:

a-1
b-1
b-2
b-3
a-2
b-4
a-3
b-5
a-4
a-5

可以看出a线程和b线程是交替执行的。

而在其中加入join()方法后(后面的代码都略去了threadtest类的定义)

package csdn;
public class testjoin {
 
 public static void main(string[] args) throws interruptedexception {
  // todo auto-generated method stub
  threadtest t1=new threadtest("a");
  threadtest t2=new threadtest("b");
  t1.start();
  t1.join();
  t2.start();
 }
}

运行结果:

a-1
a-2
a-3
a-4
a-5
b-1
b-2
b-3
b-4
b-5

显然,使用t1.join()之后,b线程需要等a线程执行完毕之后才能执行。需要注意的是,t1.join()需要等t1.start()执行之后执行才有效果,此外,如果t1.join()放在t2.start()之后的话,仍然会是交替执行,然而并不是没有效果,这点困扰了我很久,也没在别的博客里看到过。

为了深入理解,我们先看一下join()的源码。

    /**
     * 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()等同于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.
     */
    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);           //join(0)等同于wait(0),即wait无限时间直到被notify
            }
        } else {
            while (isalive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = system.currenttimemillis() - base;
            }
        }
    }

可以看出,join()方法的底层是利用wait()方法实现的。可以看出,join方法是一个同步方法,当主线程调用t1.join()方法时,主线程先获得了t1对象的锁,随后进入方法,调用了t1对象的wait()方法,使主线程进入了t1对象的等待池,此时,a线程则还在执行,并且随后的t2.start()还没被执行,因此,b线程也还没开始。等到a线程执行完毕之后,主线程继续执行,走到了t2.start(),b线程才会开始执行。

此外,对于join()的位置和作用的关系,我们可以用下面的例子来分析

package csdn;
 
public class testjoin {
 
 public static void main(string[] args) throws interruptedexception {
  // todo auto-generated method stub
  system.out.println(thread.currentthread().getname()+" start");
  threadtest t1=new threadtest("a");
  threadtest t2=new threadtest("b");
  threadtest t3=new threadtest("c");
  system.out.println("t1start");
  t1.start();
  system.out.println("t2start");
  t2.start();
  system.out.println("t3start");
  t3.start();
  system.out.println(thread.currentthread().getname()+" end");
 } 
}

运行结果为

main start
t1start
t1end
t2start
t2end
t3start
t3end
a-1
a-2
main end
c-1
c-2
c-3
c-4
c-5
a-3
b-1
b-2
b-3
b-4
b-5
a-4
a-5

a、b、c和主线程交替运行。加入join()方法后

package csdn;
 
public class testjoin {
 
 public static void main(string[] args) throws interruptedexception {
  // todo auto-generated method stub
  system.out.println(thread.currentthread().getname()+" start");
  threadtest t1=new threadtest("a");
  threadtest t2=new threadtest("b");
  threadtest t3=new threadtest("c");
  system.out.println("t1start");
  t1.start();
  system.out.println("t1end");
  system.out.println("t2start");
  t2.start();
  system.out.println("t2end");
  t1.join();
  system.out.println("t3start");
  t3.start();
  system.out.println("t3end");
  system.out.println(thread.currentthread().getname()+" end");
 } 
}

运行结果:

main start
t1start
t1end
t2start
t2end
a-1
b-1
a-2
a-3
a-4
a-5
b-2
t3start
t3end
b-3
main end
b-4
b-5
c-1
c-2
c-3
c-4
c-5

多次实验可以看出,主线程在t1.join()方法处停止,并需要等待a线程执行完毕后才会执行t3.start(),然而,并不影响b线程的执行。因此,可以得出结论,t.join()方法只会使主线程进入等待池并等待t线程执行完毕后才会被唤醒。并不影响同一时刻处在运行状态的其他线程。

ps:join源码中,只会调用wait方法,并没有在结束时调用notify,这是因为线程在die的时候会自动调用自身的notifyall方法,来释放所有的资源和锁。

到此这篇关于java多线程中join()方法的使用方法的文章就介绍到这了,更多相关java多线程join()方法内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!