7.3J.U.C值AQS-Semaphore
package com.moluo.concurrency.aqs;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private static final int THREAD_COUNT = 30;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i < THREAD_COUNT; i++) {
final int index = i;
executorService.execute(() -> {
try {
semaphore.acquire(); // 获取一个许可
test(index);
semaphore.release(); // 释放一个许可
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println("finish");
executorService.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
System.out.println(threadNum);
Thread.sleep(1000);
}
}Last updated