Semaphore 类
生活随笔
收集整理的這篇文章主要介紹了
Semaphore 类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Semaphore
Semaphore 是一種基于技術的信號量。它可以設置一個閾值,然后多個線程競爭獲取許可信號,完成后歸還,超過閾值后,線程申請許可信號將會被阻塞。
常用方法
用法
Semaphore semp = new Semaphore(5); try { // 申請許可 semp.acquire(); try { // 業務邏輯 } catch (Exception e) { } finally { // 釋放許可 semp.release(); } } catch (InterruptedException e) { } 復制代碼案例
在公共廁所只有3個坑位,但是有10個人來上廁所。那怎么辦? 假設10個人的編號分別為1-10,誰先到達,誰先搶到廁所坑位,誰就上廁所。一個坑位就是一個資源,只能一個人單獨上廁所,一個線程使用一個資源,不能共享。
package cn.lvhaosir;import java.util.Random; import java.util.concurrent.Semaphore;class Parent implements Runnable {String name;Semaphore semaphore;public Parent(String name, Semaphore semaphore) {super();this.name = name;this.semaphore = semaphore;}@Overridepublic void run() {// 獲取到資源權限,減去1,坑位減1int availablePermits = semaphore.availablePermits();if(availablePermits > 0) {// 還有資源,還有坑位System.out.println(name+"還有坑位...");} else {// 沒有資源了System.out.println(name+"怎么沒有坑位了...");}try {// 申請資源,沒有申請到的,就在此等待。有資源就繼續向下執行。semaphore.acquire();// 模擬執行步驟和所需時間System.out.println(name+"終于進入坑位...");Thread.sleep(new Random().nextInt(1000));System.out.println(name+"上完了...");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {// 釋放資源,坑位空出來了semaphore.release();}} } public class Test004 {public static void main(String[] args) throws InterruptedException {// 只有3個資源,3個坑位Semaphore semaphore = new Semaphore(3);for (int i = 1; i <= 10; i++) {new Thread(new Parent("第"+i+"個", semaphore)).start();;}} }復制代碼轉載請附上原文鏈接,有問題請留言,謝謝支持。
轉載于:https://juejin.im/post/5b553d94e51d4517c5649ab6
總結
以上是生活随笔為你收集整理的Semaphore 类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea提示,格式化代码,清除不使用的包
- 下一篇: json另类使用