package study;
import java.util.concurrent.Semaphore;
public class Test2 {
static Semaphore semaphore = new Semaphore(2,true);
public static void main(String[] args) throws InterruptedException {
for(int index = 0; index < 10; index++) {
new Thread(() -> {
boolean aquireSuccess = false;
try {
System.out.println(Thread.currentThread().getName() + "准备申请许可");
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "获得许可");
aquireSuccess = true;
Thread.sleep(1500);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (aquireSuccess) { //这样释放比较安全
semaphore.release();
System.out.println(Thread.currentThread().getName() + "成功释放许可");
}
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
}).start();
}
}
}
Semaphore的简单使用
最新推荐文章于 2022-10-17 22:56:53 发布