CountDownLatch
public class TestCountDownLatch {
public static void main ( String[ ] args) throws Exception {
CountDownLatch latch = new CountDownLatch ( 6 ) ;
for ( int i = 1 ; i <= 6 ; i++ ) {
final int num = i;
new Thread ( ( ) - > {
System. out. println ( "秦 灭" + num + "国" ) ;
latch. countDown ( ) ;
} ) . start ( ) ;
}
latch. await ( ) ;
System. out. println ( "秦统一华夏 " ) ;
}
}
CyclicBarrier
public class TestCyclicBarrier {
public static void main ( String[ ] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier ( 7 , ( ) - > System. out. println ( "========> 召唤神龙" ) ) ;
for ( int i = 1 ; i <= 7 ; i++ ) {
final int tmpInt = i;
new Thread ( ( ) - > {
try {
System. out. println ( "收集到" + tmpInt + "龙珠" ) ;
cyclicBarrier. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} catch ( BrokenBarrierException e) {
e. printStackTrace ( ) ;
}
} ) . start ( ) ;
}
}
}
Semaphore
public class TestSemaphore {
public static void main ( String[ ] args) {
int num = 5 ;
Semaphore semaphore = new Semaphore ( num) ;
for ( int i = 0 ; i < 20 ; i++ ) {
new Thread ( ( ) - > {
try {
semaphore. acquire ( ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + " 抢到位置 " + LocalDateTime. now ( ) ) ;
TimeUnit. SECONDS. sleep ( 1 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + " 吃完 " + LocalDateTime. now ( ) ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} finally {
semaphore. release ( ) ;
}
} ) . start ( ) ;
}
}
}