正常的锁(concurrency.locks或synchronized锁)在任何时刻都只允许一个任务访问一项资源,而 Semaphore允许n个任务同时访问这个资源。 package com.atnuocai.model; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Created by on 27/11/2021 *正常的锁(concurrency.locks或synchronized锁)在任何时刻都只允许一个任务访问一项资源,而 Semaphore允许n个任务同时访问这个资源。 * @author */ public class SemaphoreDemo { public static void main(String[] args) { studySemaphore(); } private static void studySemaphore() { Semaphore semaphore = new Semaphore(3);//模拟三个停车位 for (int i = 1; i<= 6 ;i++)//模拟6辆车位 { new Thread(()->{ try { semaphore.acquire(); System.out.println(Thread.currentThread().getName()+"\t 抢到车位"); try{ TimeUnit.SECONDS.sleep(3); }catch(InterruptedException e){ e. printStackTrace();} System.out.println(Thread.currentThread().getName()+"\t 抢到车位停车3秒钟离开"); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release(); } },String.valueOf(i)).start(); } } }