信号量Semaphore

信号量(Semaphore)是一个计数器,用来保护对一个或多个共享资源的访问。

信号量原理

你可以认为信号量是一个可以递增或递减的计数器。你可以初始化一个信号量的值为5,此时这个信号量可最大连续减少5次,直到计数器为0。当计数器为0时,你可以让其递增5次,使得计数器值为5。在我们的例子中,信号量的计数器始终限制在[0~5]之间。

显然,信号量并不仅仅是计数器。当计数器值为0时,它们可以使线程等待,即它们是具有计数器功能的锁。

就多线程而言,当一个线程要访问共享资源(由信号量保护)时,首先,它必须获得信号量。如果信号量的内部计数器大于0时,信号量递减计数器,并允许访问共享资源。否则,如果信号量的计数器为0,则信号量将线程置于休眠状态,直到计数器大于0。计数器中的值为0意味着所有共享资源都被其他线程使用,因此希望使用共享资源的线程必须等到有线程空闲(释放信号量)。

当一个线程完成了共享资源的使用时,它必须释放信号量,以便其他线程能够访问共享资源。该操作增加信号量的内部计数器。

如何使用信号量

PrinterQueue.java
该类表示一个打印机队列,它们控制从3个打印机中选择一个空闲的打印机打印,并在打印过程中加锁。当完成打印任务时,打印机被释放,可用于新的打印任务。
该类有2个方法getPrinter()和releasePrinter() ,分别是负责获取空闲的打印机和释放打印机。另外一个方法printJob() 实际上才是核心工作,获取打印机,执行打印任务,然后释放打印机。
它使用以下2个变量:
semaphore:这个变量跟踪在任何时间点使用打印机的数量。
printerlock:在3个可用的打印机中检查/获取空闲打印机时,锁定打印机池。

class PrinterQueue {
    //保存可用打印机的数量
    private final Semaphore semaphore;

    //当检查/获取空闲打印机时加锁
    private final Lock printerLock;

    //代表空闲的打印机池
    private boolean freePrinters[];

    public PrinterQueue() {
        semaphore = new Semaphore(3);
        freePrinters = new boolean[3];
        for (int i = 0; i < 3; i++) {
            freePrinters[i] = true;
        }
        printerLock = new ReentrantLock();
    }

    public void printJob(Object document) {
        try {
            //递减信号量计数器,标记一台打印机忙碌
            semaphore.acquire();

            //获取一台空闲打印机
            int assignedPrinter = getPrinter();

            //执行打印任务
            Long duration = (long) (Math.random() * 10000);
            System.out.println(Thread.currentThread().getName()
                    + ": Printer " + assignedPrinter
                    + " : Printing a Job during " + (duration / 1000)
                    + " seconds :: Time - " + new Date());
            Thread.sleep(duration);

            //打印任务完成; 释放打印机给其他线程.
            releasePrinter(assignedPrinter);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.printf("%s: The document has been printed\n", Thread
                    .currentThread().getName());

            //递增信号量计数器
            semaphore.release();
        }
    }

    //获取空闲打印机
    private int getPrinter() {
        int foundPrinter = -1;
        try {
            //获取锁,使得只有一个线程访问
            printerLock.lock();

            //检查哪台打印机空闲
            for (int i = 0; i < freePrinters.length; i++) {
                //找到空闲打印机,标记为忙碌
                if (freePrinters[i]) {
                    foundPrinter = i;
                    freePrinters[i] = false;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁,使得其他线程可以检查是否有空闲打印机
            printerLock.unlock();
        }
        return foundPrinter;
    }

    //释放打印机
    private void releasePrinter(int i) {
        printerLock.lock();
        //标记打印机为空闲
        freePrinters[i] = true;
        printerLock.unlock();
    }
}

PrintingJob.java
该类代表可以提交独立的打印工作给打印机。

class PrintingJob implements Runnable {
    private PrinterQueue printerQueue;

    public PrintingJob(PrinterQueue printerQueue) {
        this.printerQueue = printerQueue;
    }

    @Override
    public void run() {
        System.out.printf("%s: Going to print a document\n",
                Thread.currentThread().getName());
        printerQueue.printJob(new Object());
    }
}

测试代码

public class SemaphoreExample {
    public static void main(String[] args) {
        PrinterQueue printerQueue = new PrinterQueue();
        Thread thread[] = new Thread[10];
        for (int i = 0; i < 10; i++) {
            thread[i] = new Thread(new PrintingJob(printerQueue), "Thread " + i);
        }
        for (int i = 0; i < 10; i++) {
            thread[i].start();
        }
    }
}

执行结果

Thread 0: Going to print a document
Thread 9: Going to print a document
Thread 8: Going to print a document
Thread 7: Going to print a document
Thread 6: Going to print a document
Thread 5: Going to print a document
Thread 4: Going to print a document
Thread 3: Going to print a document
Thread 2: Going to print a document
Thread 1: Going to print a document
Thread 9: Printer 1 : Printing a Job during 4 seconds :: Time - Sat Aug 12 10:14:39 CST 2017
Thread 0: Printer 0 : Printing a Job during 1 seconds :: Time - Sat Aug 12 10:14:39 CST 2017
Thread 8: Printer 2 : Printing a Job during 2 seconds :: Time - Sat Aug 12 10:14:39 CST 2017
Thread 0: The document has been printed
Thread 7: Printer 0 : Printing a Job during 7 seconds :: Time - Sat Aug 12 10:14:41 CST 2017
Thread 8: The document has been printed
Thread 6: Printer 2 : Printing a Job during 4 seconds :: Time - Sat Aug 12 10:14:41 CST 2017
Thread 9: The document has been printed
Thread 5: Printer 1 : Printing a Job during 1 seconds :: Time - Sat Aug 12 10:14:43 CST 2017
Thread 5: The document has been printed
Thread 4: Printer 1 : Printing a Job during 8 seconds :: Time - Sat Aug 12 10:14:44 CST 2017
Thread 6: The document has been printed
Thread 3: Printer 2 : Printing a Job during 5 seconds :: Time - Sat Aug 12 10:14:46 CST 2017
Thread 7: The document has been printed
Thread 2: Printer 0 : Printing a Job during 2 seconds :: Time - Sat Aug 12 10:14:49 CST 2017
Thread 2: The document has been printed
Thread 1: Printer 0 : Printing a Job during 9 seconds :: Time - Sat Aug 12 10:14:51 CST 2017
Thread 3: The document has been printed
Thread 4: The document has been printed
Thread 1: The document has been printed

何时使用二进制信号量

很明显,二进制信号量的值可以是0或1。这意味着二进制信号量保护对单个共享资源的访问,因此信号量的内部计数器只能接受值1或0。
因此,每当你有保护对多个线程访问单个资源的要求时,就可以使用二进制信号量。

如何使用二进制信号量

为了说明二进制信号量的用法,我们将实现一个打印队列,可以由并发任务来打印它们的作业。此打印队列将受到二进制信号量的保护,因此每次只有一个线程执行打印作业。

PrinterQueue.java
该类表示打印机队列。请注意,我们将值1作为该信号量构造函数的参数传递,因此你正在创建一个二进制信号量。

public class PrinterQueue {
    private final Semaphore semaphore;

    public PrinterQueue() {
        semaphore = new Semaphore(1);
    }

    public void printJob(Object document) {
        try {
            semaphore.acquire();
            Long duration = (long) (Math.random() * 10000);
            System.out.println(Thread.currentThread().getName()
                    + ": PrintQueue: Printing a Job during " + (duration / 1000)
                    + " seconds :: Time - " + new Date());
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.printf("%s: The document has been printed\n",
                    Thread.currentThread().getName());
            semaphore.release();
        }
    }
}

执行结果

Thread 0: Going to print a document
Thread 9: Going to print a document
Thread 8: Going to print a document
Thread 7: Going to print a document
Thread 6: Going to print a document
Thread 5: Going to print a document
Thread 4: Going to print a document
Thread 3: Going to print a document
Thread 2: Going to print a document
Thread 1: Going to print a document
Thread 0: PrintQueue: Printing a Job during 7 seconds :: Time - Sat Aug 12 09:14:23 CST 2017
Thread 0: The document has been printed
Thread 9: PrintQueue: Printing a Job during 5 seconds :: Time - Sat Aug 12 09:14:30 CST 2017
Thread 9: The document has been printed
Thread 8: PrintQueue: Printing a Job during 6 seconds :: Time - Sat Aug 12 09:14:35 CST 2017
Thread 8: The document has been printed
Thread 7: PrintQueue: Printing a Job during 8 seconds :: Time - Sat Aug 12 09:14:42 CST 2017
Thread 7: The document has been printed
Thread 6: PrintQueue: Printing a Job during 0 seconds :: Time - Sat Aug 12 09:14:50 CST 2017
Thread 6: The document has been printed
Thread 5: PrintQueue: Printing a Job during 4 seconds :: Time - Sat Aug 12 09:14:51 CST 2017
Thread 5: The document has been printed
Thread 4: PrintQueue: Printing a Job during 6 seconds :: Time - Sat Aug 12 09:14:55 CST 2017
Thread 4: The document has been printed
Thread 3: PrintQueue: Printing a Job during 0 seconds :: Time - Sat Aug 12 09:15:01 CST 2017
Thread 3: The document has been printed
Thread 2: PrintQueue: Printing a Job during 3 seconds :: Time - Sat Aug 12 09:15:02 CST 2017
Thread 2: The document has been printed
Thread 1: PrintQueue: Printing a Job during 4 seconds :: Time - Sat Aug 12 09:15:05 CST 2017
Thread 1: The document has been printed

参考
1.Binary Semaphore Tutorial and Example
2.Control concurrent access to multiple copies of a resource using Semaphore

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容

  • 版权声明:本文为 cdeveloper 原创文章,可以随意转载,但必须在明确位置注明出处! 信号量 semapho...
    登龙zZ阅读 1,440评论 0 5
  • 作者: 一字马胡 转载标志 【2017-11-03】 更新日志 导入 Semaphore实现为一种基于计数的信号...
    一字马胡阅读 9,321评论 0 14
  • 很多人相信“眼见为实”,然而这一原则在营养领域却不一定适用。你所看到的,甚至你所感受到的未必是事实真相。生活中,我...
    月季舒阅读 217评论 1 0
  • 那是一条曲折的路 蜿蜒的没有风景 只余罪行在社会化显明 直等道德沦丧后的合理 当沮丧迷离 谁也无法救自己 泪水都在...
    Rivoun阅读 128评论 0 0
  • 独自, 走着望不尽头的乡路! 回忆, 拥有的和失去的一切。 仰望, 却没有一颗星辰相伴而行! 脚下 路太遥远望不尽...
    无言的路人甲阅读 182评论 0 1