您好,登錄后才能下訂單哦!
這篇文章主要介紹“什么是Semaphore”,在日常操作中,相信很多人在什么是Semaphore問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”什么是Semaphore”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
注意了,外星人放出一定量的信號(permits),其他外星人接到信號并使用(acquire),使用完后告訴發(fā)送人不再使用了(release)。如果信號被用完,只能等待。
用途:多線程運行限流、流量控制、數(shù)據(jù)庫線程池控制、控制順序執(zhí)行
提供公平和非公平的兩種方式。
class ZeroEvenOdd { private int n; private Semaphore z = new Semaphore(1); private Semaphore e = new Semaphore(0); private Semaphore o = new Semaphore(0); public ZeroEvenOdd(int n) { this.n = n; } // printNumber.accept(x) outputs "x", where x is an integer. public void zero(IntConsumer printNumber) throws InterruptedException { for(int i = 0;i<n;i++){ z.acquire(); printNumber.accept(0); if(i%2 ==0){ o.release(); }else{ e.release(); } } } public void even(IntConsumer printNumber) throws InterruptedException { for(int i = 2;i <= n;i += 2){ e.acquire(); printNumber.accept(i); z.release(); } } public void odd(IntConsumer printNumber) throws InterruptedException { for(int i = 1;i<=n;i+=2){ o.acquire(); printNumber.accept(i); z.release(); } } }
代碼中創(chuàng)建了1個信號,有3個對象共享。同一時間只有1個方法執(zhí)行,默認z有許可證,用完后通知o和e釋放,拿到資源后繼續(xù)執(zhí)行even或odd方法。
Semaphore還提供一些其他方法:
int availablePermits() :返回此信號量中當前可用的許可證數(shù)。
int getQueueLength():返回正在等待獲取許可證的線程數(shù)。
boolean hasQueuedThreads() :是否有線程正在等待獲取許可證。
void reducePermits(int reduction) :減少reduction個許可證。是個protected方法。
Collection getQueuedThreads() :返回所有等待獲取許可證的線程集合。是個protected方法。
到此,關(guān)于“什么是Semaphore”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。