Backend Development 6 min read

Understanding Java Semaphore: Methods, Usage, and Example Code

This article explains Java's Semaphore concurrency primitive, its core methods, fair vs. non‑fair modes, typical scenarios such as rate limiting and resource pooling, and provides two complete code examples demonstrating thread coordination and download throttling.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Understanding Java Semaphore: Methods, Usage, and Example Code

Semaphore (信号量) is a concurrency primitive used to coordinate threads by controlling access to shared resources through a set of permits.

Key methods include acquire() (blocks until a permit is available), release() (returns a permit), tryAcquire() (non‑blocking attempt), and availablePermits() (returns remaining permits). Semaphore can operate in fair or non‑fair mode, with fair mode granting permits in request order.

Typical use cases are rate limiting, resource‑pool management, and producer‑consumer scenarios.

Example 1 demonstrates a simple semaphore with two permits limiting four threads; each thread acquires a permit, performs a simulated task, then releases the permit. The console output shows that at most two threads run concurrently.

package com.sample.interview.multithread;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo{
    private static final Semaphore semaphore = new Semaphore(2); //创建一个信号量对象,许可证数量为2
    public static void main(String[] args) throws Exception{
        // 启动4个线程
        for (int i = 0; i < 4; i++) {
            new Thread(new MyTask("线程 - " + i)).start();
        }
    }

    static class MyTask implements Runnable{
        private final String name;

        public MyTask(String name){
            this.name = name;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(name + " 获得了许可证");
                Random random = new Random();
                int randomNum = random.nextInt(1001) + 1000;
                // 模拟执行任务
                TimeUnit.MICROSECONDS.sleep(randomNum);
            } catch (InterruptedException e){
                e.printStackTrace();
            } finally {
                System.out.println(name + " 释放了许可证");
                semaphore.release();
            }
        }
    }
}

Example 2 shows a realistic download‑limiter where a semaphore with two permits restricts simultaneous downloads. Threads attempt to acquire a permit using tryAcquire() ; if successful they simulate a download, otherwise they are throttled. The final output illustrates which files were limited and which completed.

package com.sample.interview.multithread;

import java.util.concurrent.Semaphore;

public class DownloadLimiterDemo{
    // 限制同时下载的线程数为 2
    private static final Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        // 模拟 5 个下载任务
        for (int i = 1; i <= 5; i++) {
            new Thread(new DownloadTask("文件-" + i)).start();
        }
    }

    static class DownloadTask implements Runnable{
        private final String fileName;

        public DownloadTask(String fileName) {
            this.fileName = fileName;
        }

        @Override
        public void run() {
            try {
                // 尝试获取许可(非阻塞方式)
                if (semaphore.tryAcquire()) {
                    System.out.println(fileName + " 开始下载 | 剩余并发数: " + semaphore.availablePermits());
                    Thread.sleep((long) (Math.random() * 1000)); // 模拟下载耗时
                    System.out.println(fileName + " 下载完成");
                } else {
                    System.out.println(fileName + " 被限流,请稍后重试");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release(); // 释放许可
            }
        }
    }
}

The article concludes with a call to follow the author’s WeChat channel for more programming insights.

Javabackend developmentConcurrencyMultithreadingsemaphorerate limiting
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.