005 线程的join方法

一 .概述

  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 + "已经完成任务了");
        });
    }

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

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

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

posted @ 2018-08-21 19:09  最爱五仁月饼  阅读(102)  评论(0编辑  收藏  举报