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();
        }
    }
}

.并发

相关文章
相关标签/搜索