java中Thread.join()方法

1. Thread.join()方法是什么
Thread.join()方法是Thread类中的一个方法,该方法的定义是等待该线程终止。其实就是join()方法将挂起调用线程的执行, 直到被调用的线程完成它的执行。
举例说明:在主线程中调用t1.join()方法,主线程将等待t1线程终止。join()方法挂起主线程的执行,直到t1执行完毕后主线程才接着执行。
2. Thread.join如何使用
现在有T1、T2两个线程,你怎样保证T2在T1执行完后执行?

public class ThreadJoin {

    public static void main(String[] args){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    System.out.println("thread t1 is running");
                    Thread.sleep(5000);
                    System.out.println("thread t1 is over");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //t1.join();
                    System.out.println("thread t2 is running");
                    Thread.sleep(5000);
                    System.out.println("thread t2 is over");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
    }

运行结果如下:

thread t2 is running
thread t1 is running
thread t1 is over
thread t2 is over

可以看出t2并没有等待t1执行结束后才执行,两者是并发执行的。

使用Thread.join()方法,在线程t2中执行t1.join()方法,此时调用线程是t2,被调用线程是t1,t2将等待t1执行结束后才执行。
运行结果如下:

thread t1 is running
thread t1 is over
thread t2 is running
thread t2 is over

此时t1、t2是顺序执行的。

文章转载自: https://blog.csdn.net/a158123/article/details/78633772

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值