package com.zhy.test;import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Semaphore;public class SemaphoreTest
{ private static int mCarNum = 20;
private static Semaphore semaphore = new Semaphore(mCarNum); public static void main(String[] args) throws InterruptedException
{ for (int i = 0; i < 100; i++)
{
new Thread()
{
public void run()
{
try
{
String peopleName = createPeople();
takeCar(peopleName);
} catch (InterruptedException e)
{
e.printStackTrace();
}
};
}.start(); } } private static String createPeople() throws InterruptedException
{
Thread.sleep(new Random().nextInt(3000));
return Thread.currentThread().getName(); } /**
 * 坐车
 * 
 * @throws InterruptedException
 */
public static void takeCar(String peopleName) throws InterruptedException
{
semaphore.acquire();
raogongyuan(peopleName);
} /**
 * 绕公园
 * 
 * @throws InterruptedException
 */
private static void raogongyuan(String peopleName)
throws InterruptedException
{
System.out.println(peopleName + "游园中...,剩余车辆 :"
+ semaphore.availablePermits());
Thread.sleep(new Random().nextInt(5000)+3000);
semaphore.release(); }}
假设有20量车,则信号量为20,没来一个人消耗一辆车,则信号量-1,游园完成则释放一辆车,信号量+1;具体自己测试。
对并发有兴趣可以看http://blog.csdn.net/lmj623565791/article/details/26810813  有并发一系列的文章