java.util.concurrent 下的Semaphore CyclicBarrier CountDownLatch 分析使用

来源:互联网 发布:淘宝免费开店是真的吗 编辑:程序博客网 时间:2024/05/24 07:12
package com.ai.runner.test.lock;import java.sql.Timestamp;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CountDownLatch;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.Semaphore;/** * Semaphore * CyclicBarrier * CountDownLatch * @date 2017年4月18日 * @author zhoushanbin * */public class SemaphoreCyclicBarrierCountDownLatchTest {public static void main(String args[]){//downLatchTest();//cyclicBarrier();semaphoreTest();}/** * Semaphore 主要用于控制并发访问 * new Semaphore(count) 中count为“准入许可数量”,线程通过acquire() 接口申请“准入许可”,当“准入许可”数量还有时,则该线程 * 持有“准入许可”继续运行,运行完后,归还“准入许可”;当“准入许可”数量不够时,则线程阻塞,直到获取“准入许可” * @author think * @ApiDocMethod * @ApiCode * @RestRelativeURL */public static void semaphoreTest(){int count = 2;final Semaphore semp = new Semaphore(count);for(int i=0;i<50;i++){new Thread(){@Overridepublic void run() {System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"检查是否可运行");try {semp.acquire();System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"开始运行");Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}finally{System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"运行结束");semp.release();}}}.start();}}/** * CyclicBarrier 相当一个屏障,所有的线程都将阻塞在屏障的await()上,直到所有线程都调用了await,线程才往下运行 * Waits until all parties have invoked await on this barrier * @author think * @ApiDocMethod * @ApiCode * @RestRelativeURL */public static void cyclicBarrier(){int count = 50;final CyclicBarrier barrier = new CyclicBarrier(count);  for(int i=0;i<count;i++){try {Thread.sleep(100);} catch (InterruptedException e1) {e1.printStackTrace();}new Thread(){@Overridepublic void run() {try {System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"准备好了");barrier.await();System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"开始运行");} catch (BrokenBarrierException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}finally{}}}.start();}}/** * 可用于阻塞主线线程,直到所有子线程执行完后,主线程才继续运行 *  * @author think * @ApiDocMethod * @ApiCode * @RestRelativeURL */public static void downLatchTest(){int count = 5;final CountDownLatch latch = new CountDownLatch(count);for(int i=0;i<count;i++){new Thread(){@Overridepublic void run() {System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"开始运行");try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}finally{System.out.println(new Timestamp(System.currentTimeMillis())+":"+Thread.currentThread().getName()+"运行结束");latch.countDown();}}}.start();}try {latch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("运行完毕");}}

0 0
原创粉丝点击