欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中的信號(hào)量Semaphore詳細(xì)解讀

 更新時(shí)間:2023年11月20日 11:05:06   作者:tanxinji  
這篇文章主要介紹了Java中的信號(hào)量Semaphore詳細(xì)解讀,Java信號(hào)量機(jī)制可以用來保證線程互斥,創(chuàng)建Semaphore對(duì)象傳入一個(gè)整形參數(shù),類似于公共資源,需要的朋友可以參考下

Java中的信號(hào)量Semaphore

信號(hào)量機(jī)制可以用來保證線程互斥

創(chuàng)建Semaphore對(duì)象: 傳入一個(gè)整形參數(shù),類似于公共資源

常用方法:

  • acquire();獲取一個(gè)公共資源,公共資源-1,如果公共資源小于等于0阻塞等待
  • acquire(int permits);獲取permits個(gè)公共資源,公共資源-permits,如果公共資源<0阻塞等待
  • release();釋放一個(gè)公共資源,公共資源+1
  • release(int permits);釋放permits個(gè)公共資源,公共資源+permits
  • boolean tryAcquire( );嘗試獲取一個(gè)公共資源,可以獲取返回true,不可以返回false
  • boolean tryAcquire( int permits );嘗試獲取permits個(gè)公共資源,可以獲取返回true,不可以返回false
		Semaphore s = new Semaphore(1);
        s.acquire();
        s.release();

示例:

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        Semaphore t = new Semaphore(1);

        new Thread(  ()->{
            try {
              t.acquire(  );  // 獲取
              Thread.sleep(2000);
              System.out.println(Thread.currentThread().getName()+" 執(zhí)行!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                t.release(); //釋放
            }

        } ,"thread1" ).start();

        new Thread(  ()->{
            try {
                t.acquire();
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName()+" 執(zhí)行!");

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                t.release(1);
            }
        } ,"thread2" ).start();



    }
}

到此這篇關(guān)于Java中的信號(hào)量Semaphore詳細(xì)解讀的文章就介紹到這了,更多相關(guān)信號(hào)量Semaphore內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論