Java多線程的Semaphore

Semaphore 信號量, 在多線程應用中, 用來控制同時訪問某個特定資源的操做數量, 或者同時執行某個指定操做的數量, 還能夠用來實現某種資源池限制, 或者對容器施加邊界. 簡單地說, Semaphore就是synchronized的增強版, 能夠控制線程的併發數量.java

控制對某一方法併發的訪問數量多線程

public class DemoSemaphore {
    # 1表示同時只容許1個線程訪問, 3則表示3個
    private Semaphore semaphore = new Semaphore(3);

    public void exec() {
        try {
            semaphore.acquire();
            long threadId = Thread.currentThread().getId();
            System.out.println(threadId + " acquired");
            long rand = (long)(Math.random() * 1000);
            Thread.sleep(rand);
            System.out.println(threadId + " end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) {
        DemoSemaphore demo = new DemoSemaphore();
        for (int i = 0; i < 30; i++) {
            new Thread(demo::exec).start();
        }
    }
}

.併發

相關文章
相關標籤/搜索