Java多线程之Semaphore基础篇

111 阅读1分钟

一、Semaphore应用场景

  • 主要用来控制系统中最大的并发执行的线程数,可以运用到需要进行限流的业务场景

二、一个简单Demo搞懂Semaphore

public class MySemaphore {
    /*Semaphore(10);相当于通过构造函数创造了10个供线程运行的位置*/
    private static Semaphore semaphore = new Semaphore(10);
    private static Thread[] threads = new Thread[20];
    public static void main(String[] args) {
        for (int i = 0; i < threads.length; i++) {
           threads[i] = new Thread(()->{
                try {
                    /*当10个位置未满时,当前线程则占用一个位置,程序继续往下执行,
                    * 当位置满了当前线程则阻塞
                    * */
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    /*
                    *此处相当于线程运行完后将位置归还,归还的位置可以继续供其他线程调用
                    * 此处如果注释的话相当于线程执行完后没有让出位置,因此执行完10个线程程序将会阻塞
                    * */
                    semaphore.release();
                }
            });
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }
}