停车场的停车位数量是固定的,Semaphore就像是停车场的管理员控制总的停车数量,如果车位已满,只能出一辆进一辆
Semaphore semaphore=new Semaphore(2);
控制车位数是2,默认不是公平的
Semaphore semaphore=new Semaphore(2,true);
车位数是2,公平锁,先到先停车
package com.vincent.juc; import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit; /** * Vincent 创建于 2016/6/1. * 信号灯 */public class SemaphoreDemo { public static void main(String[] args) { final Semaphore semaphore=new Semaphore(2,true); ExecutorService threadPool = Executors.newCachedThreadPool(); final Random random=new Random(); for(int i=0;i<10;i++){ threadPool.execute(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); try { semaphore.acquire(); System.out.println(id+"获取到锁"); int t = random.nextInt(5); TimeUnit.SECONDS.sleep(t+1); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println(id+"释放锁"); semaphore.release(); } } }); } }}
输出:
12获取到锁13获取到锁12释放锁14获取到锁13释放锁17获取到锁17释放锁15获取到锁14释放锁18获取到锁15释放锁16获取到锁18释放锁19获取到锁19释放锁20获取到锁16释放锁21获取到锁21释放锁20释放锁