java Smaphore 控制併發線程數

概念:java

  Semaphore(信號量)是用來控制同事訪問特定資源的線程數量,它經過協調各個線程,已保證合理的使用公共資源。數據庫

應用場景:併發

  Semaphore 能夠用於作流量控制,特別是共用資源有限的應用場景,好比數據庫鏈接。假若有一個需求,要讀取幾萬個文件的數據,由於都是IO密集型任務,咱們能夠啓動幾十個線程併發的讀取,可是若是讀到內存後,還須要存儲到數據庫中。而數據庫的鏈接數只有10個,這時咱們必須控制只有10個線程同時獲取數據庫鏈接保存數據,不然報錯沒法獲取數據庫鏈接。這個時候,就能夠使用Semaphore來作流量控制。ide

package com.test;

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 ++) {
            threadPool.execute(new Runnable() {
                
                @Override
                public void run() {
                    try {
                        s.acquire();
                        System.out.println("save DATA:" + System.currentTimeMillis());
                        s.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                }
            });
        }
        threadPool.shutdown();
    }
}
相關文章
相關標籤/搜索