java技术基础多线程专家

二进制Semaphore教程和示例

2019-03-03  本文已影响1人  步积

semaphore是一个计数器,它保护对一个或多个共享资源的访问。在本教程中,我们将学习如何使用二进制semaphore来控制多线程对共享资源的访问。

Semaphores是如何工作的?

可以将semaphore想象成计数器,计数器可以递增或递减。用一个数字(即5)初始化semaphore。现在这个semaphore可以连续减少最多5次,直到计数器达到0。一旦计数器为0,您可以将其增加5次,使其最大为5。semaphore的计数器值必须始终在限制0 >= n >= 5的范围内(在本例中)。

显然,semaphore不仅仅是计数器。当计数器值为0时,它们能够使线程等待,也就是说,它可以充当具有计数器功能的锁。

从多线程的角度来说,当一个线程想要访问一个共享资源(由semaphore保护)时,首先,它必须获得这个semaphore。如果semaphore的内部计数器大于0,则semaphore递减计数器并允许访问共享资源。否则,如果semaphore的计数器为0,semaphore将使线程休眠,直到计数器大于0。计数器中的值为0意味着所有共享资源都被其他线程使用,因此希望使用其中一个资源的线程必须等到其中一个资源空闲出来。

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

什么时候使用二进制Semaphore?

很明显,二进制semaphore可以是0或1。这意味着二进制semaphore保护对单个共享资源的访问,因此信号量的内部计数器只能接受值1或0。

因此,当您需要保护对多线程访问的单个资源的访问时,可以使用二进制semaphore

阅读更多:如何在Java中使用锁

如何使用二进制Semaphore?

为了展示二进制semaphore的用法,我们将实现一个打印队列,并发任务可以使用该队列打印它们的作业。这个打印队列将受到二进制semaphore的保护,因此一次只能打印一个线程。

PrintingJob.java

这个类表示可以提交给打印机的独立打印。这个类实现Runnable接口,这样打印机就可以在轮到它时执行它。

public class PrintingJob implements Runnable {
    private PrinterQueue printerQueue;

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

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

PrinterQueue.java

该类表示打印机队列/打印机。请注意,我们将值1作为这个semaphore的构造函数的参数传递,因此您正在创建一个二进制semaphore

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();
        }
    }
}

让我们测试一下打印程序:

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: PrintQueue: Printing a Job during 2 seconds :: Time - Sun Mar 03 13:46:03 CST 2019
Thread 9: The document has been printed
Thread 8: PrintQueue: Printing a Job during 2 seconds :: Time - Sun Mar 03 13:46:06 CST 2019
Thread 8: The document has been printed
Thread 6: PrintQueue: Printing a Job during 4 seconds :: Time - Sun Mar 03 13:46:09 CST 2019
Thread 6: The document has been printed
Thread 7: PrintQueue: Printing a Job during 4 seconds :: Time - Sun Mar 03 13:46:13 CST 2019
Thread 7: The document has been printed
Thread 5: PrintQueue: Printing a Job during 7 seconds :: Time - Sun Mar 03 13:46:17 CST 2019
Thread 5: The document has been printed
Thread 4: PrintQueue: Printing a Job during 9 seconds :: Time - Sun Mar 03 13:46:25 CST 2019
Thread 4: The document has been printed
Thread 3: PrintQueue: Printing a Job during 4 seconds :: Time - Sun Mar 03 13:46:35 CST 2019
Thread 3: The document has been printed
Thread 2: PrintQueue: Printing a Job during 1 seconds :: Time - Sun Mar 03 13:46:39 CST 2019
Thread 2: The document has been printed
Thread 0: PrintQueue: Printing a Job during 5 seconds :: Time - Sun Mar 03 13:46:41 CST 2019
Thread 0: The document has been printed
Thread 1: PrintQueue: Printing a Job during 1 seconds :: Time - Sun Mar 03 13:46:46 CST 2019
Thread 1: The document has been printed

查看printJob()方法。此方法展示了在使用semaphore实现临界区和保护对共享资源的访问时必须遵循的三个步骤:

  1. 首先,使用acquire()方法获取semaphore
  2. 然后,对共享资源执行必要的操作。
  3. 最后,使用release()方法释放semaphore

Semaphore类的构造函数中允许第二个参数。此参数必须采用布尔值。如果您给它false值,您就创建了一个semaphore,它将在非公平模式下工作。这是默认选项。如果您给它true值,您就创建了一个semaphore,它将在公平模式下工作。

参考资料
Binary Semaphore Tutorial and Example

上一篇下一篇

猜你喜欢

热点阅读