使用场景:用于仅能提供有限访问的资源,比如数据库的最大链接数
package io.haitaoc.concurrency.example.aqs;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreExample1 {
private final static int threadCount = 200;
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(20);
/**
* 200个请求,每次并发数只有20个
*/
for (int i = 0; i <threadCount ; i++) {
final int threadNum = i;
exec.execute(()->{
try {
semaphore.acquire(); //获取一个许可
test(threadNum);
semaphore.release(); //释放许可
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println("finish");
exec.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
System.out.println(threadNum);
Thread.sleep(1000);
}
}
处理多个许可
package io.haitaoc.concurrency.example.aqs;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreExample2 {
private final static int threadCount = 200;
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
/**
* 200个请求,每次并发数只有3个
*/
for (int i = 0; i <threadCount ; i++) {
final int threadNum = i;
exec.execute(()->{
try {
semaphore.acquire(3); //获取多个许可
test(threadNum);
semaphore.release(3); //释放多个许可
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println("finish");
exec.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
System.out.println(threadNum);
Thread.sleep(1000);
}
}
只有三个线程输出了结果,其他都被丢弃,往线程池里放入20个请求,semaphore会让每个线程尝试获取许可,但是同一时间内并发数是3,相当于只有三个线程获取到了许可,所以只有三个线程执行
package io.haitaoc.concurrency.example.aqs;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreExample3 {
private final static int threadCount = 200;
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
/**
* 200个请求,每次并发数只有3个
*/
for (int i = 0; i <threadCount ; i++) {
final int threadNum = i;
exec.execute(()->{
try {
if(semaphore.tryAcquire()){
test(threadNum);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println("finish");
exec.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
System.out.println(threadNum);
Thread.sleep(1000);
}
}
output:
0
1
5
finish
网友评论