実現1.joinの方法
のみ()開始を呼び出した後に参加し、
呼び出し元のスレッドは、サブスレッドの実行が終了した後に待っています
パブリック クラスThreadJoinTest { 公共 静的 ボイドメイン(文字列[]引数){ int型のカウント= 100 。 []のスレッドがスレッド = 新しいスレッドを[カウント]。 IntStream.range( 0 、カウント) .forEach(I - > { スレッド[i]は = 新しいスレッド( "スレッド" + I){ @Override 公共 ボイドラン(){ ThreadJoinTest.sleep( 1 ); System.out.println(にThread.currentThread()のgetName()。 + ":" + I); } }; スレッド[I] .start(); }); // スタートに参加する唯一の呼び出し(後) / / スレッドを呼び出すと、実行しているサブスレッドの終了後にお待ちしております Arrays.stream(スレッド).forEach(ThreadJoinTest ::参加); System.out.printlnは(「オーバー」); }
プライベート 静的 ボイド睡眠(int型秒){ しようと{ TimeUnit.SECONDS.sleep(秒)。 } キャッチ(InterruptedExceptionあるのEX){ } } プライベート 静的 ボイドは参加(スレッドスレッド){ しようと{ (thread.joinを)。 } キャッチ(InterruptedExceptionあるのEX){ } }
次のように試験結果であります
スレッド2:2 thread10: 10 thread6: 6 thread14: 14 thread18: 18 thread34: 34 thread22: 22 thread26: 26 thread30: 30 thread38: 38 thread42: 42 thread46: 46 thread50: 50 thread54: 54 thread62: 62 thread66: 66 thread58: 58 thread70: 70 thread74: 74 thread78: 78 thread82: 82 thread86: 86 thread90: 90 thread94: 94 thread98: 98 thread5: 5 スレッド1: 1 thread9: 9 thread13: 13 thread17: 17 thread21: 21 thread25: 25 thread29: 29 thread33: 33 thread37: 37 thread41: 41 thread45: 45 thread49: 49 thread61: 61 thread57: 57 thread53: 53 thread77: 77 thread73: 73 thread69: 69 thread65: 65 thread93:93 thread89: 89 thread85: 85 thread81: 81 thread97: 97 thread0: 0 thread12: 12 thread4: 4 thread8: 8 thread16: 16 thread20: 20 thread24: 24 thread28: 28 thread32: 32 thread36: 36 thread40: 40 thread44: 44 thread60 : 60 thread56: 56 thread52: 52 thread48: 48 thread76: 76 thread72: 72 thread68: 68 thread64: 64 thread92: 92 thread88: 88 thread84: 84 thread80: 80 thread96: 96 thread3: 3 thread7: 7 thread11: 11 thread99: 99 thread95: 95 thread91: 91 thread87: 87 thread83: 83 thread79: 79 thread75: 75 thread67: 67 thread63: 63 thread71: 71 thread59: 59 thread51: 51 thread55:55 thread23: 23 thread27: 27 thread31: 31 thread35: 35 thread39: 39 thread43: 43 thread47: 47 thread15: 15 thread19: 19 を超えます
2. java.util.concurrent.CountDownLatch
パブリック クラスThreadJoinTest { 公共 静的 ボイドメイン(文字列[]引数){ int型のカウント= 100 。 []のスレッドがスレッド = 新しいスレッドを[カウント]。 java.util.concurrent.CountDownLatchたCountDownLatch = 新しいjava.util.concurrent.CountDownLatch(カウント)。 IntStream.range( 0 、カウント) .forEach(I - > { スレッド[i]は = 新しいスレッド( "スレッド" + I){ @Override 公共 のボイドラン(){ ThreadJoinTest.sleep( 1。;) のSystem.out.println(にThread.currentThread()のgetName()。 + ":" + I);
//は、最終的なプロセスで実行、または最後にtry..finallyのことができます countDownLatch.countDown(); } }; スレッド[I] .start(); }); 試み{ CountDownLatch.await(); } キャッチ(InterruptedExceptionあるEX){ } のSystem.out.println( "上" ); }