semaphore说明

semaphore说明

介绍

一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。

示例

Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。例如,下面的类使用信号量控制对内容池的访问:

package com.chen.concurrent;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	public static void main(String[] args) {
		SemaphoreTest semaphoreTest = new SemaphoreTest();
		
		semaphoreTest.test01();
	}
	
	public void test01(){
		Semaphore semaphore = new Semaphore(10);//定义有10个停车位
		
		final Park park = new Park(semaphore);
		
		//创建让车出停车场的线程
		Thread t_letCarOut = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					while(true){
						Thread.sleep(5000);
						park.letGoout();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		t_letCarOut.start();
		
		for(int i = 0;i < 100;i++){
	
			park.letGoin("car"+i);
		}
		
		
	}
	
	public class Park{
		
		private Semaphore semaphore;
		
		public Park(Semaphore semaphore) {
			this.semaphore = semaphore;
		}
		
		public void letGoin(String carName){
			try {
				System.out.println(carName+"存放汽车进入停车场");
				if(semaphore.availablePermits() == 0){
					System.out.println("现在车位不够了,无法进入停车场!");
				}
				semaphore.acquire();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public void letGoout(){
			try {
				System.out.println("放汽车出停车场");
				semaphore.release();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值