victory的博客

长安一片月,万户捣衣声

0%

并发 | Semaphore

Semaphore

Semaphore(信号量)是用来控制同时访问特定资源的数量,它通过协调各个线程,以保证合理的使用公共资源。
应用场景:
Semaphore可以用于做流量控制,特别是公共资源优先的应用场景,比如数据库连接
示例代码:

package concurrency.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    private static final int THREAD_COUNT = 30;
    
    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
    
    private static Semaphore s = new Semaphore(10);
    
    public static void main(String[] args) {
        for(int i = 0; i < THREAD_COUNT; i++){//虽然有30个线程在执行,但是只允许10个并发执行
            threadPool.execute(new Runnable(){
                @Override
                public void run(){
                    try{
                        s.acquire();
                        System.out.println("save data");
                        s.release();
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}