JUC中的同步辅助类
CountDownLatch
public class CountDownLatchDemo {
public static void main ( String[ ] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch ( 3 ) ;
for ( int i = 1 ; i <= 3 ; i++ ) {
new Thread ( ( ) - > {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "go" ) ;
countDownLatch. countDown ( ) ;
} , i+ "" ) . start ( ) ;
}
countDownLatch. await ( ) ;
System. out. println ( "全部执行完毕!!!" ) ;
}
}
CyclicBarrier
public class CyclicBarrierDemo {
public static void main ( String[ ] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier ( 5 , ( ) - > {
System. out. println ( "当计数器达到5时,才会执行这里的业务" ) ;
} ) ;
for ( int i = 0 ; i < 5 ; i++ ) {
new Thread ( ( ) - > {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "\t执行了\t\t还有" + ( 4 - cyclicBarrier. getNumberWaiting ( ) ) + "个线程在等待" ) ;
try {
cyclicBarrier. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} catch ( BrokenBarrierException e) {
e. printStackTrace ( ) ;
}
} , i+ "" ) . start ( ) ;
}
}
}
Semaphore
public class SemaphoreDemo {
public static void main ( String[ ] args) {
Semaphore semaphore = new Semaphore ( 3 ) ;
for ( int i = 1 ; i <= 6 ; i++ ) {
new Thread ( ( ) - > {
try {
semaphore. acquire ( ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "得到运行条件,开始运行" ) ;
TimeUnit. SECONDS. sleep ( 2 ) ;
System. out. println ( Thread. currentThread ( ) . getName ( ) + "运行结束,释放资源" ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
semaphore. release ( ) ;
}
} , i+ "号" ) . start ( ) ;
}
}
}