package com.han.demo01;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class TestXHL {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);//单个参数为资源数量
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
try {
semaphore.acquire();//获取资源
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "抢到了车位");
try {
TimeUnit.SECONDS.sleep(2);//停车两秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "离开了车位");
semaphore.release();//释放资源
}, String.valueOf(i)).start();
}
}
}
Semaphore信号量使用(限流)
于 2022-05-10 21:53:24 首次发布