005 線程的join方法

來源:互聯網
上載者:User

標籤: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方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.