Java 8 - juc - Semaphore

import java.util.concurrent.Semaphore;

/**
 * Semaphore是一个同步工具类,用于控制同时访问某个资源的线程数量。
 * 它通过维护一定数量的许可证(permits)来实现并发控制。
 *
 * 当一个线程要访问资源时,首先需要从Semaphore获取许可证,如果有可用的许可证,则线程可以继续执行,许可证数量减少。
 * 如果没有可用的许可证,线程将被阻塞,直到有许可证可用。
 *
 * 当线程完成对资源的访问后,需要释放许可证,以便其他线程可以获取并访问资源。
 */
public class SemaphoreExample {
    
    
    private static final int MAX_CONCURRENT_THREADS = 3;
    private static final Semaphore semaphore = new Semaphore(MAX_CONCURRENT_THREADS);

    public static void main(String[] args) {
    
    
        Thread[] threads = new Thread[5];

        for (int i = 0; i < threads.length; i++) {
    
    
            threads[i] = new Thread(new Worker("Thread " + (i + 1)));
            threads[i].start();
        }

        for (Thread thread : threads) {
    
    
            try {
    
    
                thread.join();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    static class Worker implements Runnable {
    
    
        private final String name;

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

        @Override
        public void run() {
    
    
            try {
    
    
                System.out.println(name + " is trying to acquire a permit.");
                semaphore.acquire(); // 获取许可证
                System.out.println(name + " has acquired a permit.");

                // 模拟线程执行一些任务
                Thread.sleep(2000);

                System.out.println(name + " is releasing the permit.");
                semaphore.release(); // 释放许可证
                System.out.println(name + " has released the permit.");
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/130937280