Semaphore实现并发数限制

百度百科解释:Semaphore是一种在多线程环境下使用的设施,该设施负责协调各个线程,以保证它们能够正确、合理的使用公共资源的设施,也是操作系统中用于控制进程同步互斥的量。

Semaphore是java并发包下的一个工具类,可以控制多线程对共享资源的访问,acquire()获取一个许可,如果没有就等待,而release()释放一个许可。如某个方法只允许最多10个线程并发访问,则实现代码如下:

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

public class SemaphoreDemo {

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        // 最多10个线程同时访问
        final Semaphore semaphore = new Semaphore(10);
        // 20个线程同时启动
        for (int i = 1; i <= 20; i++) {
            final int index = i;
            exec.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 获取许可
                        semaphore.acquire();
                        // 调用资源
                        callRomote(index);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        // 访问完后,释放
                        semaphore.release();
                        //availablePermits()指的是当前库中有多少个许可可以被使用
                        System.out.println("availablePermits => " + semaphore.availablePermits());
                    }
                }
            });
        }
        // 退出线程池
        exec.shutdown();
    }

    /**
     * 被调用资源
     *
     * @param arg
     */
    public static void callRomote(int arg) {
        System.out.println("arg: " + arg);
        try {
            Thread.sleep((long) (Math.random() * 6000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章