---
title: "concurrent包,多线程信号量Semaphore"
author: "myemptyname"
date: "2012-11-22T16:13:47Z"
tags: ["Semaphore", "concurrent", "java多线程", "信号量"]
categories: ["编程语言"]
slug: "concurrent-semaphore"
draft: false
lastmod: "2012-11-22T17:10:57Z"
id: 1733386
url: "https://chanmao.iteye.com/blog/1733386"
---

信号量大家都不陌生引用百度百科上的解释

     信号量：在多[线程](http://baike.baidu.com/view/1053.htm)环境下使用的一种设施，是可以用来保证两个或多个关键[代码段](http://baike.baidu.com/view/1315853.htm)不被并发调用。在进入一个关键代码段之前，线程必须获取一个信号量；一旦该关键代码段完成了，那么该线程必须释放信号量。其它想进入该关键代码段的线程必须等待直到第一个线程释放信号量。

     下面学习一下concurrent包下的 Semaphore 类

      举个恶心的例子：蹲茅坑，现在有5个坑，有20个人在排队等着5个坑，那么只有等其中一个人上完了厕所以后，另外一个才能进去。

      Semaphore 正是实现了这种功能。

 

```
import java.util.concurrent.*;

/**
 * 
 * @author myemptyname
 *
 */

public class TestSemaphore {

	public static void main(String[] args) {
		 // 动态扩展线程池 
		ExecutorService exec = Executors.newCachedThreadPool();
		// 只有5个茅坑 
		final Semaphore semp = new Semaphore(5);
		// 20个人憋不住了
		for (int index = 0; index < 20; index++) {
			final int NO = index;
			Runnable run = new Runnable() {
				public void run() {
					try {
						 //排队看看有没有空坑，有就进去  
						semp.acquire();
						System.out.println(NO+"号上厕所: ");
						Thread.sleep((long) (Math.random() * 10000));
						// 上完了 舒服
						semp.release();
						System.out.println(NO+"出厕所");
						System.out.println("现在有"+ semp.availablePermits()+"个茅坑");

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			exec.execute(run);
		}
		// 退出线程池
		exec.shutdown();
	}

}
```