CountDownLatch
public class CountDownLatchDemo { // Princípio: // countDownLatch.countDown (); // Quantity-1 // countDownLatch.await (); // Aguarde o contador retornar a zero e execute novamente // Sempre que um thread chamar countDown ( ) Número -1, assumindo que o contador se torne 0, countDownLatch.await () será acordado e continuará sendo executado! public static void main (String [] args) lança InterruptedException { // O número total é 6, quando a tarefa deve ser executada, use CountDownLatch count = new CountDownLatch ( 6 ); for ( int i = 0 ; i <= 6 ; i ++) { new Thread (() -> { System. out .println (Thread.currentThread (). getName () + " Sair " ); count.countDown (); // Número menos um }, String.valueOf (i )). start (); } count. waitit (); // Aguarde o contador retornar para 0 e, em seguida, execute System. out .println ( " Fechar porta " ); // count.countDown (); } }
CyclicBarrier
1 classe pública CyclicBarrierDemo { 2 public static void main (String [] args) { 3 // Se o número definido for maior que o número no loop, os insatisfeitos no loop ficarão bloqueados em barreira.await (); aguarde aqui 4 CyclicBarrier barreira = new CyclicBarrier ( 9 , () -> { 5 System. out .println ( " Invocar Deus Dragão " ); 6 }); 7 8 9 para ( int i = 0 ; i <= 7 ; i ++ ) { 10 int temp = i; 11 // lambda 12 novo Thread (() -> { 13 System. Out .println (Thread.currentThread (). GetName () + " 收集" + temp + " 个 龙珠" ); 14 try { 15 barreira . wait (); 16 } catch (InterruptedException e) { 17 e.printStackTrace (); 18 } catch (BrokenBarrierException e) { 19 e.printStackTrace (); 20 } 21 }). Start (); 22 } 23 } 23 }
Semáforo
1 classe pública SemahoreDome { 2 public static void main (String [] args) { 3 // Número de threads, o limite de espaço de estacionamento será usado 4 5 Semáforo semáforo = novo Semáforo ( 3 ); 6 7 for ( int i = 0 ; i <= 6 ; i ++ ) { 8 novo Thread (() -> { 9 // adquire () obtém 10 try { 11 semaphore.acquire (); 12 System. Out .println (Thread.currentThread (). GetName () + " Obter espaço para estacionamento " ); 13 TimeUnit.SECONDS.sleep ( 2 ); 14 System. Out .println (Thread.currentThread (). GetName () + " Sair do estacionamento " ); 15 } catch (InterruptedException e) { 16 e.printStackTrace (); 17 } finalmente { 18 semaphore.release (); // release () release 19 } 20 }, String.valueOf (i)). Start (); 21 } 22 23 } 24 }