zoukankan      html  css  js  c++  java
  • Semaphore 使用详解

    1. Semaphore 是什么?

    Semaphore 字面意思是信号量的意思,它的作用是控制访问特定资源的线程数目。

    2. 怎么使用 Semaphore?

    2.1 构造方法

    public Semaphore(int permits)
    public Semaphore(int permits, boolean fair)

    解析:

    • permits 表示许可线程的数量
    • fair 表示公平性,如果这个设为 true 的话,下次执行的线程会是等待最久的线程

    2.2 重要方法

    public void acquire() throws InterruptedException
    public void release()

    解析:

    • acquire() 表示阻塞并获取许可
    • release() 表示释放许可

    2.3 基本使用

    2.3.1 需求

    多个线程同时执行,但是限制同时执行的线程数量为 2 个。

    2.3.2 代码实现

    public class SemaphoreDemo {
    
        static class TaskThread extends Thread {
    
            Semaphore semaphore;
    
            public TaskThread(Semaphore semaphore) {
                this.semaphore = semaphore;
            }
    
            @Override
            public void run() {
                try {
                    semaphore.acquire();
                    System.out.println(getName() + " acquire");
                    Thread.sleep(1000);
                    semaphore.release();
                    System.out.println(getName() + " release ");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            int threadNum = 5;
            Semaphore semaphore = new Semaphore(2);
            for (int i = 0; i < threadNum; i++) {
                new TaskThread(semaphore).start();
            }
        }
    
    }

    打印结果:

    Thread-1 acquire
    Thread-0 acquire
    Thread-0 release 
    Thread-1 release 
    Thread-2 acquire
    Thread-3 acquire
    Thread-2 release 
    Thread-4 acquire
    Thread-3 release 
    Thread-4 release 

    从打印结果可以看出,一次只有两个线程执行 acquire(),只有线程进行 release() 方法后才会有别的线程执行 acquire()。

    需要注意的是 Semaphore 只是对资源并发访问的线程数进行监控,并不会保证线程安全。

    3. Semaphore 使用场景

    可用于流量控制,限制最大的并发访问数。

     https://mp.weixin.qq.com/s/8m_RhTyVftgc5UX6ABX2vA

    故乡明
  • 相关阅读:
    [转]好习惯养成的10个步骤
    模拟资料
    [转]暗时间
    [转]30个小改变,造就你的卓越人生
    [转]Word 2007文档中图片不显示或对象不显示的解决方法
    ubuntu 10.04 安转2.6.38内核
    [转]可以让你少奋斗10年的工作经验
    [转]Vim 复制粘帖格式错乱问题的解决办法
    C# 获取类中所有的属性
    sql 脚本
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15124088.html
Copyright © 2011-2022 走看看