Semaphore 信号量小解

时间:2022-02-13 15:14:01

Semaphore :和synchronized 、lock有点像,限制线程数量访问临街资源。

附上demo

public class TestClass {

    public static void main(String[] args) {

         Semaphore semaphore = new Semaphore(5);

        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();
        new Thread(new SemaphoreClass(semaphore)).start();

    }
}


class SemaphoreClass implements Runnable {
    private Semaphore semaphore ;

    SemaphoreClass(Semaphore semaphore){
        this.semaphore = semaphore;
    }

    @Override
    public void run() {

        try {
            System.out.println(Thread.currentThread().getName()+"--等待授权--");
            Thread.sleep(2000);
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+"--已经授权--");
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName()+"--处理事情--");
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName()+"--处理完了--");
            System.out.println(Thread.currentThread().getName()+"--释放资源--");
            semaphore.release();
            System.out.println(Thread.currentThread().getName()+"--资源已经释放--");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}