CountDownLatch
public class CountDownLatchDemo { // Principle: // countDownLatch.countDown (); // Quantity-1 // countDownLatch.await (); // Wait for the counter to return to zero, and then execute again // Every time a thread calls countDown ( ) Number -1, assuming the counter becomes 0, countDownLatch.await () will be woken up and continue to execute! public static void main (String [] args) throws InterruptedException { // The total number is 6, when the task must be executed, then use CountDownLatch count = new CountDownLatch ( 6 ); for ( int i = 0 ; i <= 6 ; i ++) { new Thread (()-> { System. out .println (Thread.currentThread (). getName () + " Go out " ); count.countDown (); // Number minus one }, String.valueOf (i )). start (); } count. await (); // Wait for the counter to return to 0, and then execute down System. out .println ( " Close Door " ); // count.countDown (); } }
CyclicBarrier
1 public class CyclicBarrierDemo { 2 public static void main (String [] args) { 3 // If the set number is larger than the number in the loop, the dissatisfaction in the loop will be stuck in barrier.await (); wait here 4 CyclicBarrier barrier = new CyclicBarrier ( 9 , ()-> { 5 System. out .println ( " Summon God Dragon " ); 6 }); 7 8 9 for ( int i = 0 ; i <= 7 ; i ++ ) { 10 int temp = i; 11 //lambda能操作 i 吗 12 new Thread(()->{ 13 System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠"); 14 try { 15 barrier.await(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } catch (BrokenBarrierException e) { 19 e.printStackTrace (); 20 } 21 }). Start (); 22 } 23 } 23 }
Semaphore
1 public class SemahoreDome { 2 public static void main (String [] args) { 3 // Number of threads, parking space limit will be used 4 5 Semaphore semaphore = new Semaphore ( 3 ); 6 7 for ( int i = 0 ; i <= 6 ; i ++ ) { 8 new Thread (()-> { 9 // acquire () gets 10 try { 11 semaphore.acquire (); 12 System. Out .println (Thread.currentThread (). GetName () + " Get parking space " ); 13 TimeUnit.SECONDS.sleep ( 2 ); 14 System. Out .println (Thread.currentThread (). GetName () + " Leave the parking lot " ); 15 } catch (InterruptedException e) { 16 e.printStackTrace (); 17 } finally { 18 semaphore.release (); // release () release 19 } 20 },String.valueOf(i)).start(); 21 } 22 23 } 24 }