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

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

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

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

  • 相关阅读:
    Android 下拉刷新上啦加载SmartRefreshLayout + RecyclerView
    Maven 本地打war包
    数据库性能优化一
    SessionStateMode之Redis共享session
    SessionStateMode之SQL Server共享session
    iframe跨域
    Jenkins发布MVC应用程序
    Docker入门之一Docker在Window下安装
    Window下SVN服务器搭建以及客户端使用
    Window下Jenkins的安装
  • 原文地址:https://www.cnblogs.com/trekxu/p/9513346.html
Copyright © 2020-2023  润新知