【Java 并发编程实战】信号量 (Semaphore)

作者: 光剑书架上的书 | 来源:发表于2020-02-11 17:55 被阅读0次

    解决什么问题的?

    信号量 (Semaphore), 限制同时执行代码的线程数量
    Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

    它并不能解决安全问题,而是用来限制最大的并发量。

    1965年,荷兰学者Edsger Dijkstra提出的信号量(Semaphores)机制是一种卓有成效的进程同步工具,在长期广泛的应用中,信号量机制得到了极大的发展,它从整型信号量经记录型信号量,进而发展成为“信号量集机制”,信号量机制已经被广泛的应用到单处理机和多处理机系统以及计算机网络中。

    代码实战

        package com.light.sword
    
    import java.util.concurrent.Semaphore
    
    /**
     * @author: Jack
     * 2020-02-10 15:42
     */
    
    object SemaphoreDemo {
        fun task(semaphore: Semaphore) {
            semaphore.acquire()
    
            Thread.sleep(3000)
            val currentThread = Thread.currentThread()
            val name = currentThread.name
            println("${System.currentTimeMillis()}:$name")
    
            semaphore.release()
        }
    }
    
    fun main() {
        val s = Semaphore(3) // 限制同时执行代码的线程数量为3. 如果为1,就是一个普通的互斥锁
        for (i in 0..30) {
            Thread {
                SemaphoreDemo.task(s)
            }.start()
        }
    }
    // 输出
    1581320963993:Thread-30
    1581320963993:Thread-0
    1581320963993:Thread-29
    
    1581320966996:Thread-28
    1581320966996:Thread-26
    1581320966996:Thread-27
    
    1581320970000:Thread-24
    1581320970000:Thread-25
    1581320970000:Thread-23
    
    1581320973002:Thread-5
    1581320973002:Thread-1
    1581320973002:Thread-4
    
    1581320976006:Thread-6
    1581320976006:Thread-7
    1581320976006:Thread-3
    
    1581320979007:Thread-9
    1581320979007:Thread-22
    1581320979007:Thread-8
    
    1581320982011:Thread-10
    1581320982011:Thread-11
    1581320982011:Thread-12
    
    1581320985016:Thread-13
    1581320985016:Thread-2
    1581320985016:Thread-14
    
    1581320988017:Thread-15
    1581320988017:Thread-21
    1581320988017:Thread-16
    
    1581320991021:Thread-17
    1581320991021:Thread-19
    1581320991021:Thread-18
    
    1581320994026:Thread-20
    ...
    

    怎样解决的?

    keys=4

    keys=3

    AQS: mechanics via AbstractQueuedSynchronizer

    AbstractQueuedSynchronizer(AQS)

    类如其名,抽象的队列式的同步器,AQS定义了一套多线程访问共享资源的同步器框架,许多同步类实现都依赖于它,如常用的ReentrantLock/Semaphore/CountDownLatch...。

    A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire blocks if necessary until a permit is available, and then takes it. Each release adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

    Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource. For example, here is a class that uses a semaphore to control access to a pool of items:

     class Pool {
       private static final int MAX_AVAILABLE = 100;
       private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
    
       public Object getItem() throws InterruptedException {
         available.acquire();
         return getNextAvailableItem();
       }
    
       public void putItem(Object x) {
         if (markAsUnused(x))
           available.release();
       }
    
       // Not a particularly efficient data structure; just for demo
    
       protected Object[] items = ... whatever kinds of items being managed
       protected boolean[] used = new boolean[MAX_AVAILABLE];
    
       protected synchronized Object getNextAvailableItem() {
         for (int i = 0; i < MAX_AVAILABLE; ++i) {
           if (!used[i]) {
              used[i] = true;
              return items[i];
           }
         }
         return null; // not reached
       }
    
       protected synchronized boolean markAsUnused(Object item) {
         for (int i = 0; i < MAX_AVAILABLE; ++i) {
           if (item == items[i]) {
              if (used[i]) {
                used[i] = false;
                return true;
              } else
                return false;
           }
         }
         return false;
       }
     }
    

    Before obtaining an item each thread must acquire a permit from the semaphore, guaranteeing that an item is available for use. When the thread has finished with the item it is returned back to the pool and a permit is returned to the semaphore, allowing another thread to acquire that item. Note that no synchronization lock is held when acquire is called as that would prevent an item from being returned to the pool. The semaphore encapsulates the synchronization needed to restrict access to the pool, separately from any synchronization needed to maintain the consistency of the pool itself.

    A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many java.util.concurrent.locks.Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

    The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. In particular, barging is permitted, that is, a thread invoking acquire can be allocated a permit ahead of a thread that has been waiting - logically the new thread places itself at the head of the queue of waiting threads. When fairness is set true, the semaphore guarantees that threads invoking any of the acquire methods are selected to obtain permits in the order in which their invocation of those methods was processed (first-in-first-out; FIFO). Note that FIFO ordering necessarily applies to specific internal points of execution within these methods. So, it is possible for one thread to invoke acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed tryAcquire methods do not honor the fairness setting, but will take any permits that are available.

    Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kinds of synchronization control, the throughput advantages of non-fair ordering often outweigh fairness considerations.

    This class also provides convenience methods to acquire and release multiple permits at a time. Beware of the increased risk of indefinite postponement when these methods are used without fairness set true.

    Memory consistency effects: Actions in a thread prior to calling a "release" method such as release() happen-before actions following a successful "acquire" method such as acquire() in another thread.

    Since: 1.5 @author Doug Lea

    参考资料

    https://baike.baidu.com/item/%E4%BF%A1%E5%8F%B7%E9%87%8F/9807501?fr=aladdin


    Kotlin 开发者社区

    国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

    越是喧嚣的世界,越需要宁静的思考。

    相关文章

      网友评论

        本文标题:【Java 并发编程实战】信号量 (Semaphore)

        本文链接:https://www.haomeiwen.com/subject/ixpwnctx.html