Home  >  Article  >  Java  >  How to use Semaphore to implement current limiting in Java?

How to use Semaphore to implement current limiting in Java?

WBOY
WBOYforward
2023-04-21 20:34:061405browse

Concept

1. Semaphore can be regarded as a semaphore that has been widely translated into a semaphore. Conceptually, a semaphore maintains a set of credentials, and the thread that obtains the credentials can Access resources and release them after use. We can use semaphores to limit concurrent threads accessing specific resources.

2. It can be simply summarized as: a counter, a waiting queue, and three methods. In the semaphore model, counters and waiting queues are transparent and can only be accessed through the three methods provided by the semaphore model, namely Internet, acquire and release.

Example

public class SemaphoreDemo {
 
    static class Link {
    }
 
    static class ObjPool<T, R> {
 
        final List<T> pool;
 
        final Semaphore semaphore;
 
        ObjPool(int size, T t) {
            pool = new Vector<>(size);
            for (int i = 0; i < size; i++) {
                pool.add(t);
            }
            semaphore = new Semaphore(size);
        }
 
        public R exec(Function<T, R> func) throws Exception {
            T t = null;
            semaphore.acquire();
            try {
                System.out.println(Thread.currentThread().getName() + "---------争夺锁--------");
 
                t = pool.remove(0);
                System.out.println(Thread.currentThread().getName() + " 拿到锁执行");
                return func.apply(t);
            } finally {
                pool.add(t);
                semaphore.release();
            }
        }
    }
 
    public static void main(String[] args) {
        ObjPool objPool = new ObjPool(5, new Link());
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                try {
                    objPool.exec(t -> t.toString());
                } catch (Exception e) {
                }
            }).start();
        }
    }
}

The above is the detailed content of How to use Semaphore to implement current limiting in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete