Thread synchronization class: Semaphore

Semaphore: thread resource control access to the number of classes

Construction method:

// permits为访问线程的数量
Semaphore semaphore = new Semaphore(int permits);

Main methods:
Semaphore.acquire (): Gets licensed to run, and block other threads
semaphore.release (): release permit, allow other threads to run

scenes to be used:

The control of the code with a maximum of two threads executing
the code:
thread class:

class JymSemaphoreThread implements Runnable{
    // 控制访问线程资源数量类
    private Semaphore semaphore;

    public JymSemaphoreThread(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    public void run() {
        try {
            // 获取运行许可,并阻塞其他线程
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "阻塞并获取许可");
            // 释放许可,让其他线程运行
            System.out.println(Thread.currentThread().getName() + "释放许可");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Test code:

    public static void main(String[] args) {
    	// 每次最多两个线程访问资源,当有线程调用release方法后才会有线程进入
        Semaphore semaphore = new Semaphore(2);
        JymSemaphoreThread jymSemaphoreThread = new JymSemaphoreThread(semaphore);
        for(int i = 0 ; i<5 ;i++){
            new Thread(jymSemaphoreThread).start();
        }
    }

result:
Here Insert Picture Description

Lack of study time, too shallow knowledge, that's wrong, please forgive me.

There are 10 kinds of people in the world, one is to understand binary, one is do not understand binary.

Published 71 original articles · won praise 54 · views 420 000 +

Guess you like

Origin blog.csdn.net/weixin_43326401/article/details/104121396