當(dāng)前位置:
首頁 >
Semaphore 类
發(fā)布時(shí)間:2025/3/20
35
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Semaphore 类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Semaphore
Semaphore 是一種基于技術(shù)的信號量。它可以設(shè)置一個(gè)閾值,然后多個(gè)線程競爭獲取許可信號,完成后歸還,超過閾值后,線程申請?jiān)S可信號將會(huì)被阻塞。
常用方法
用法
Semaphore semp = new Semaphore(5); try { // 申請?jiān)S可 semp.acquire(); try { // 業(yè)務(wù)邏輯 } catch (Exception e) { } finally { // 釋放許可 semp.release(); } } catch (InterruptedException e) { } 復(fù)制代碼案例
在公共廁所只有3個(gè)坑位,但是有10個(gè)人來上廁所。那怎么辦? 假設(shè)10個(gè)人的編號分別為1-10,誰先到達(dá),誰先搶到廁所坑位,誰就上廁所。一個(gè)坑位就是一個(gè)資源,只能一個(gè)人單獨(dú)上廁所,一個(gè)線程使用一個(gè)資源,不能共享。
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() {// 獲取到資源權(quán)限,減去1,坑位減1int availablePermits = semaphore.availablePermits();if(availablePermits > 0) {// 還有資源,還有坑位System.out.println(name+"還有坑位...");} else {// 沒有資源了System.out.println(name+"怎么沒有坑位了...");}try {// 申請資源,沒有申請到的,就在此等待。有資源就繼續(xù)向下執(zhí)行。semaphore.acquire();// 模擬執(zhí)行步驟和所需時(shí)間System.out.println(name+"終于進(jìn)入坑位...");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個(gè)資源,3個(gè)坑位Semaphore semaphore = new Semaphore(3);for (int i = 1; i <= 10; i++) {new Thread(new Parent("第"+i+"個(gè)", semaphore)).start();;}} }復(fù)制代碼轉(zhuǎn)載請附上原文鏈接,有問題請留言,謝謝支持。
轉(zhuǎn)載于:https://juejin.im/post/5b553d94e51d4517c5649ab6
總結(jié)
以上是生活随笔為你收集整理的Semaphore 类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea提示,格式化代码,清除不使用的包
- 下一篇: json另类使用