CountDownLatch
import java. util. concurrent. CountDownLatch;
import java. util. concurrent. TimeUnit;
public class CountDownLatchDemo {
public static final int NUM = 6 ;
public static void main ( String[ ] args) {
CountDownLatch latch = new CountDownLatch ( NUM) ;
for ( int i = 1 ; i <= NUM; i++ ) {
new Thread ( ( ) - > {
try {
TimeUnit. SECONDS. sleep ( 1 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "员工下班" ) ;
latch. countDown ( ) ;
} , String. valueOf ( i) ) . start ( ) ;
}
try {
latch. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( "管理员锁门" ) ;
}
}
CyclicBarrier
import java. util. concurrent. CyclicBarrier;
import java. util. concurrent. TimeUnit;
public class CyclicBarrierDemo {
public static void main ( String[ ] args) {
CyclicBarrier barrier = new CyclicBarrier ( 7 , ( ) - > {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "召唤神龙" ) ;
} ) ;
for ( int i = 1 ; i <= 7 ; i++ ) {
final int tmp = i;
new Thread ( ( ) - > {
try {
TimeUnit. SECONDS. sleep ( 1 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "收集到第" + tmp + "颗龙珠" ) ;
try {
barrier. await ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
} , String. valueOf ( i) ) . start ( ) ;
}
}
}
Semaphore
import java. util. concurrent. Semaphore;
import java. util. concurrent. TimeUnit;
public class SemaphoreDemo {
public static void main ( String[ ] args) {
Semaphore semaphore = new Semaphore ( 3 ) ;
for ( int i = 0 ; i < 6 ; i++ ) {
new Thread ( ( ) - > {
try {
semaphore. acquire ( ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "抢到车位" ) ;
TimeUnit. SECONDS. sleep ( 3 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "停3秒后离开" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} finally {
semaphore. release ( ) ;
}
} , String. valueOf ( i) ) . start ( ) ;
}
}
}