JUC辅助类 CountDownLatch CyclicBarrier Semaphore

CountDownLatch 减法计数器

public class A {
    
    

	public static void main(String[] args) {
    
    
		//总数是6,必须要执行的任务的时候 使用
		CountDownLatch countDownLatch = new CountDownLatch(6);
		
		for (int i = 0; i < 6; i++) {
    
    
			new Thread(()->{
    
    
				countDownLatch.countDown();
				System.out.println(Thread.currentThread().getName()+"离开");
			},String.valueOf(i)).start();
		}
		
		//等待计数器归零 在向下执行
		try {
    
    
			countDownLatch.await();
		} catch (InterruptedException e) {
    
    
			e.printStackTrace();
		}
		System.out.println("关门");
	}
}
countDownLatch.countDown();  数量减一
countDownLatch.await(); 等待计数器归零,在向下执行

CyclicBarrier 加法计数器

public class CyclicBarrierTest {
    
    

	public static void main(String[] args) {
    
    
		/**
		 * 7颗龙珠召唤神龙
		 */
		CyclicBarrier barrier = new CyclicBarrier(7,()->{
    
    
			System.out.println("召唤神龙成功!");
		}) ;
		
		for (int i = 1; i <= 7; i++) {
    
    
			final int temp = i;
			//lambda能操作i么
			new Thread(()->{
    
    
				System.out.println(Thread.currentThread().getName()+ ":"+temp);
			
				try {
    
    
					barrier.await();
				} catch (InterruptedException | BrokenBarrierException e) {
    
    
					e.printStackTrace();
				}
			},String.valueOf(i)+"线程") .start();
		}
	}
}

barrier.await(); 等待计数器到自定义数量,在向下执行

Semaphore 信号量 (限流)

/**
 * 停车位举例  3个车位 
 * 6个车
 */
public class SemaphoreTest {
    
    

	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(1);
					System.out.println(Thread.currentThread().getName()+"离开车位");
				} catch (InterruptedException e) {
    
    
					e.printStackTrace();
				} finally {
    
    
					//释放车位
					semaphore.release();
				}
				
			},String.valueOf(i)+"号车").start();
		}
	}
}

semaphore.acquire(); 获取,如果已经满了就等到被释放为止
semaphore.release(); 释放,会将当前信号量释放 ,唤醒等待线程

猜你喜欢

转载自blog.csdn.net/jj89929665/article/details/112969074