zoukankan      html  css  js  c++  java
  • 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 + "已经完成任务了");
            });
        }

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

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

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

  • 相关阅读:
    UVA 10618 Tango Tango Insurrection
    UVA 10118 Free Candies
    HDU 1024 Max Sum Plus Plus
    POJ 1984 Navigation Nightmare
    CODEVS 3546 矩阵链乘法
    UVA 1625 Color Length
    UVA 1347 Tour
    UVA 437 The Tower of Babylon
    UVA 1622 Robot
    UVA127-"Accordian" Patience(模拟)
  • 原文地址:https://www.cnblogs.com/trekxu/p/9513346.html
Copyright © 2011-2022 走看看