Thread.join()方法

Thread.join()方法

        作用:调用线程等待该线程完成后,才能继续往下运行。

public static void main(String[] args) throws InterruptedException{
    System.out.println("main start");

    Thread t1 = new Thread(new Worker("thread-1"));
    t1.start();
    t1.join();
    System.out.println("main end");
}

       在上面的例子中,main 线程要等到 t1 线程运行结束后,才会输出"main end"。如果不加 t1.join(),main线程和 t1 线程是并行的。而加上t1.join(),程序就变成是顺序执行了。

       我们在用到 join() 的时候,通常都是 main 线程等到其他多个线程执行完毕后再继续执行。其他多个线程之间并不需要互相等待。

下面这段代码并没有实现让其他线程并发执行,线程是顺序执行的。

public static void main(String[] args) throws InterruptedException {
    System.out.println("main start");

    Thread t1 = new Thread(new Worker("thread-1"));
    Thread t2 = new Thread(new Worker("thread-2"));
    t1.start();
    //等待t1结束,这时候t2线程并未启动
    t1.join();

    //t1结束后,启动t2线程
    t2.start();
    //等待t2结束
    t2.join();

    System.out.println("main end");
}

为了让 t1、t2 线程并行,我们可以稍微改一下代码,下面给出完整的代码:

public class JoinTest {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main start");

        Thread t1 = new Thread(new Worker("thread-1"));
        Thread t2 = new Thread(new Worker("thread-2"));

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

        t1.join();
        t2.join();

        System.out.println("main end");
    }
}
class Worker implements Runnable {

    private String name;

    public Worker(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name);
        }
    }
}

Thread.join()方法,介绍到此为止

如果本文对你有所帮助,那就给我点个赞呗 ^_^ 

End

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值