package com.njust.test.learn;

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

public class SemaphoreDemo
{
    public static void main(String[] args)
    {
        ExecutorService executorService = Executors.newCachedThreadPool();
        
        Semaphore semaphore = new Semaphore(5);
        
        for (int i = 0; i < 10; i++)
        {
            executorService.execute(() -> {
                
                //获取锁
                try
                {
                    semaphore.acquire();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 已进入: <---");
                
                try
                {
                    Thread.sleep((long)(Math.random() * 1000));
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                
                //释放锁
                semaphore.release();
                System.out.println(
                    Thread.currentThread().getName() + " 已退出: ---> ");
                //因为不在semaphore的acquire和release形成的锁范围内，availablePermits的值可能不对
                System.out.println("当前可用个数(接近的):" + semaphore.availablePermits());
                
            });
        }
        
        executorService.shutdown();
    }
}

@@ -148,16 +148,418 @@
 phore;%0A%0A
+/**%0A * %3Cpre%3E%0A * pool-1-thread-1 %E5%B7%B2%E8%BF%9B%E5%85%A5: %3C---%0A * pool-1-thread-2 %E5%B7%B2%E8%BF%9B%E5%85%A5: %3C---%0A * pool-1-thread-3 %E5%B7%B2%E8%BF%9B%E5%85%A5: %3C---%0A * pool-1-thread-2 %E5%B7%B2%E9%80%80%E5%87%BA: ---%3E%0A * %E5%BD%93%E5%89%8D%E5%8F%AF%E7%94%A8%E4%B8%AA%E6%95%B0(%E6%8E%A5%E8%BF%91%E7%9A%84):1%0A * pool-1-thread-5 %E5%B7%B2%E8%BF%9B%E5%85%A5: %3C---%0A * pool-1-thread-3 %E5%B7%B2%E9%80%80%E5%87%BA: ---%3E%0A * pool-1-thread-4 %E5%B7%B2%E8%BF%9B%E5%85%A5: %3C---%0A * %E5%BD%93%E5%89%8D%E5%8F%AF%E7%94%A8%E4%B8%AA%E6%95%B0(%E6%8E%A5%E8%BF%91%E7%9A%84):0%0A * pool-1-thread-1 %E5%B7%B2%E9%80%80%E5%87%BA: ---%3E%0A * %E5%BD%93%E5%89%8D%E5%8F%AF%E7%94%A8%E4%B8%AA%E6%95%B0(%E6%8E%A5%E8%BF%91%E7%9A%84):1%0A * pool-1-thread-5 %E5%B7%B2%E9%80%80%E5%87%BA: ---%3E%0A * %E5%BD%93%E5%89%8D%E5%8F%AF%E7%94%A8%E4%B8%AA%E6%95%B0(%E6%8E%A5%E8%BF%91%E7%9A%84):2%0A * pool-1-thread-4 %E5%B7%B2%E9%80%80%E5%87%BA: ---%3E%0A * %E5%BD%93%E5%89%8D%E5%8F%AF%E7%94%A8%E4%B8%AA%E6%95%B0(%E6%8E%A5%E8%BF%91%E7%9A%84):3%0A * %3C/pre%3E%0A */%0A
 public c
@@ -756,17 +756,17 @@
 maphore(
-5
+3
 );%0A     
@@ -797,18 +797,17 @@
  0; i %3C 
-10
+5
 ; i++)%0A 

Update SemaphoreDemo.java