多线程中的join()方法

本文介绍Java多线程中的join方法,演示了如何使用该方法实现线程间的协作,确保主线程等待子线程完成后再继续执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在java的多线程中有一个join()方法,作用是等待其他的线程结束。一直不明白是怎么回事,今天查了一下资料才了解,简单的说一下吧。

join()方法是java多线程中的一种协作机制,比如我们现在有一个线程运行着,运行到了某个位置,我们需要另外一个线程返回的人结果,这个时候,我们就需要在当前线程中调用另外一个线程的join()方法,注意是另外一个线程的join()方法,表示当前线程需要等待另外一个线程的完成。等到另外一个线程完成之后,再从join()方法的后面开始执行

一个简单的demo如下:

package com.app.basic;

/**
 * Created by Charles on 2016/2/1.
 */
public class JoinMotion {

    public static void main(String[] args) {

        final Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("current thread is:"+Thread.currentThread().getName());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

        final Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
              for(int i =0; i < 7;i++){
                  System.out.println("current thread is:"+Thread.currentThread().getName());
                  try {
                      Thread.sleep(1000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  if(i == 3){
                      try {
                          t1.join();
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                  }
              }
            }
        });

        t1.start();
        t2.start();

    }
}

返回的结果如下:

current thread is:Thread-0
current thread is:Thread-1
current thread is:Thread-0
current thread is:Thread-1
current thread is:Thread-0
current thread is:Thread-1
current thread is:Thread-0
current thread is:Thread-1
current thread is:Thread-0
current thread is:Thread-1
current thread is:Thread-1
current thread is:Thread-1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值