前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Java 并发编程实战】信号量 (Semaphore)

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

作者头像
一个会写诗的程序员
发布2020-02-18 17:39:09
9540
发布2020-02-18 17:39:09
举报
文章被收录于专栏:一个会写诗的程序员的博客

解决什么问题的?

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

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

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

代码实战

代码语言:javascript
复制
    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:

代码语言:javascript
复制
 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、函数式编程、编程思想等相关主题。

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解决什么问题的?
  • 代码实战
  • 怎样解决的?
    • AbstractQueuedSynchronizer(AQS)
    • 参考资料
    • Kotlin 开发者社区
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档