码迷,mamicode.com
首页 > 编程语言 > 详细

005 线程的join方法

时间:2018-08-21 19:45:10      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:bsp   stream   结果   art   使用   ati   arraylist   sleep   oid   

一 .概述

  join()方法可以让一个线程等待另外一个线程运行结束,同时join()方法具有可打断性,也就是说,在一定的时间点,线程可以不再等待继续执行.

  下面我们首先看一下这个例子.

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            IntStream.rangeClosed(1, 100).
                forEach((e)-> {
                    System.out.println(Thread.currentThread().getName() + "-- " + e);
                } );
        })  ;
        
        t.start();
        t.join();
        System.out.println("main thread is runnging...");
        
    }

我们发现,执行的结果表明,主线程是在子线程完全执行完毕才会执行的.

通过这个例子,我们可以知道,主线程是会等到子线程完全执行完毕才会执行的.


 

二 .使用join()完成任务分发和收集  

private static List<String> result =null;
    static {
        result = new ArrayList<>();
        Collections.synchronizedCollection(result);
    }
    
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = getThread(1);
        Thread t2 = getThread(2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        
        result.stream().forEach(System.out::println);
    }
    
    private static Thread getThread(long seconds) {
        return new Thread(()-> {
            try {
                TimeUnit.SECONDS.sleep(seconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String threadName = Thread.currentThread().getName();
            result.add(threadName);
            System.out.println(threadName + "已经完成任务了");
        });
    }

在上面的例子之中,我们首先常见了两个线程分别作子任务,将结果收集到一个容器之中.

当子线程完成任务的时候,我们的主线程继续执行,现在的结果容器之中就有了结果.

那么,主线程就可以通过子结果完成自己的任务收集工作了.

005 线程的join方法

标签:bsp   stream   结果   art   使用   ati   arraylist   sleep   oid   

原文地址:https://www.cnblogs.com/trekxu/p/9513346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!