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