- package cn.itcast.gz;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Semaphore;
- public class SemaphoreTest {
- public static void main(String[] args) {
- ExecutorService service = Executors.newFixedThreadPool(10);
- //定义3盏信号灯
- final Semaphore sp = new Semaphore(3);
- for(int i = 0;i<10;i++)
- {
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- try {
- //获取信号灯
- sp.acquire();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("线程"+Thread.currentThread().getName()+
- "进入,当前已有"+(3-sp.availablePermits())+"个线程");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("线程"+Thread.currentThread().getName()+"即将离开");
- sp.release();
- }
- };
- //把10个任务逐一放到线程池中执行
- service.execute(runnable);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/030120148388.html
来源: http://www.codesnippet.cn/detail/030120148388.html