怎么形象化的理解Java中的加入(join)线程?

thread.join() 方法的解释是 "Waits for this thread to die",即"等待这个线程死亡",比如 threadxxx.join() 时就是"等待 线程xxx 死亡",当然这句话时缺少一个主语的,谁等待?是执行这句代码的线程等待,比如在main 方法中有 threadxxx.join() ,就是说主线程会等待线程xxx死亡后再向下执行 threadxxx.join()之后的代码, 对于新手来说,感觉怪怪的,有一个例子可以体会该方法的价值。想必大家都会写计算一个方法执行时间的代码吧,无非是得到起止的时间差,可是在多线程环境下,该方法未必奏效,比如:

public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        for( int i=0;i<10;i++ ){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getId() + " start...");
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getId() + " stop...");
                }
            }).start();
        }
        long t2 = System.currentTimeMillis();
        System.out.println( "take " + ( t2-t1 ) + " milliseconds" );
}

这种方法对吗?当执行到最后一句时,可能有的线程还未执行完,所以不对,知识后就用到join了,看看join的定义,在这里就是当所有的线程执行完之后主方法在执行,下面是正确做法:

public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        List<Thread> threads = new ArrayList<>();
        for( int i=0;i<10;i++ ){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getId() + " start...");
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getId() + " stop...");
                }
            });
            thread.start();
            threads.add( thread );
        }
        for( Thread thread:threads ){
            try {
                thread.join();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println( "take " + ( t2-t1 ) + " milliseconds" );
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值