您当前的位置: 首页 >  Java

java持续实践

暂无认证

  • 3浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java多线程 join的作用和普通用法

java持续实践 发布时间:2020-08-30 13:39:31 ,浏览量:3

文章目录
      • join方法的作用 用法
      • join普通用法的demo

join方法的作用 用法

作用: 因为新的线程加入了我们, 所以我们要等待他执行完再执行. (例如等待某些初始化的线程执行完毕, 再执行. )

用法: main线程等待子线程执行完毕. (注意是main线程等待子线程)

join普通用法的demo

如下的代码, 子线程使用了join. 因此main线程会进行等待子线程执行完毕, 才会打印出"所有子线程执行完毕"

package com.thread.threadobjectclasscommonmethods;

/**
 * 类名称:Join
 * 类描述: 演示join,注意语句输出顺序,会变化。
 *
 * @author: https://javaweixin6.blog.csdn.net/
 * 创建时间:2020/8/30 13:27
 * Version 1.0
 */
public class Join {

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行完毕");
            }
        },"thread1");

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行完毕");
            }
        },"thread2");

        thread1.start();
        thread2.start();

        System.out.println("开始等待子线程运行完毕");
        thread1.join();
        thread2.join();
        System.out.println("所有子线程执行完毕");
    }


}

程序运行的结果如下 如果把join线程去掉, 那么就会出现如下的线程, main线程并没有等待子线程, 直接打印出了"所有子线程执行完毕"

关注
打赏
1658054974
查看更多评论
立即登录/注册

微信扫码登录

0.1487s