Java Semaphore

Semaphore简介
        Semaphore是一个计数信号量,它的本质是一个"共享锁"。

信号量维护了一个信号量许可集。线程可以通过调用acquire()来获取信号量的许可;当信号量中有可用的许可时,线程能获取该许可;否则线程必须等待,直到有可用的许可为止。 线程可以通过release()来释放它所持有的信号量许可。

关于Semaphore的详细介绍可参考:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html


Semaphore 函数列表

Modifier and Type	Method and Description
void	acquire()
Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.
void	acquire(int permits)
Acquires the given number of permits from this semaphore, blocking until all are available, or the thread is interrupted.
void	acquireUninterruptibly()
Acquires a permit from this semaphore, blocking until one is available.
void	acquireUninterruptibly(int permits)
Acquires the given number of permits from this semaphore, blocking until all are available.
int	availablePermits()
Returns the current number of permits available in this semaphore.
int	drainPermits()
Acquires and returns all permits that are immediately available.
protected Collection<Thread>	getQueuedThreads()
Returns a collection containing threads that may be waiting to acquire.
int	getQueueLength()
Returns an estimate of the number of threads waiting to acquire.
boolean	hasQueuedThreads()
Queries whether any threads are waiting to acquire.
boolean	isFair()
Returns true if this semaphore has fairness set true.
protected void	reducePermits(int reduction)
Shrinks the number of available permits by the indicated reduction.
void	release()
Releases a permit, returning it to the semaphore.
void	release(int permits)
Releases the given number of permits, returning them to the semaphore.
String	toString()
Returns a string identifying this semaphore, as well as its state.
boolean	tryAcquire()
Acquires a permit from this semaphore, only if one is available at the time of invocation.
boolean	tryAcquire(int permits)
Acquires the given number of permits from this semaphore, only if all are available at the time of invocation.
boolean	tryAcquire(int permits, long timeout, TimeUnit unit)
Acquires the given number of permits from this semaphore, if all become available within the given waiting time and the current thread has not been interrupted.
boolean	tryAcquire(long timeout, TimeUnit unit)
Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been interrupted.

Semaphore示例

最近自己做的一个项目中,需要控制某一资源的数量,多线程并发访问的时候,如果资源已经分配完了则当前线程需要等待直到有其它线程释放资源,一个简单的示例Demo如下:

package com.ricky.java.test.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	private static final int PERMITS = 3;
	
	private static final int THREAD_NUM = 8;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		//信号量的数目,也可理解为资源的数目
		Semaphore semaphore = new Semaphore(PERMITS);
		
		//创建线程池
		ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_NUM);
		
		for(int i=0;i<THREAD_NUM;i++){
			threadPool.execute(new Worker(semaphore, i));
		}
		
		//关闭线程池
		threadPool.shutdown();
	}
	
	public static class Worker implements Runnable{
		
		private Semaphore semaphore;
		private int id;
		
		public Worker(Semaphore semaphore,int id){
			this.id = id;
			this.semaphore = semaphore;
		}
		
		@Override
		public void run() {
			
			try {
				
				System.out.println("Worker_"+id + " acquire...");
				
				semaphore.acquire();
				
				Thread.sleep(2000);
				
				System.out.println("Worker_"+id+" run...");
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				semaphore.release();
			}
		}
		
	}

}

执行结果如下:

Worker_2 acquire...
Worker_0 acquire...
Worker_1 acquire...
Worker_7 acquire...
Worker_4 acquire...
Worker_6 acquire...
Worker_3 acquire...
Worker_5 acquire...
Worker_0 run...
Worker_2 run...
Worker_1 run...
Worker_7 run...
Worker_4 run...
Worker_6 run...
Worker_5 run...
Worker_3 run...


      每次都只能有3个线程获取到信号量,并打印System.out.println("Worker_"+id+" run..."); 这句话。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值