咱們知道獨佔鎖能夠實現臨界資源一次只能被一個線程訪問,但若是想實現多個線程同時訪問的話就要用到信號量Semaphore——記錄一個共享資源被訪問線程的個數,Semeahore更像是一個共享鎖,當它的許可數爲1的時候就至關於獨佔鎖了;acquire(int n)拿許可,一次可拿多個、tryAcquire()嘗試拿許可boolean,也可設置嘗試獲取時間、release()釋放許可;ide
public class SamephoreDemo { static Semaphore sema=new Semaphore(2); public static class task implements Runnable{ @Override public void run() { try { sema.acquire();//拿許可 Thread.sleep(2000);//模擬耗時 System.out.println(Thread.currentThread().getName()+"完成"); } catch (InterruptedException e) { e.printStackTrace(); }finally { sema.release();//釋放許可 } } } public static void main(String[] args) { ExecutorService executorService=Executors.newFixedThreadPool(8); for(int i=0;i<16;i++){ executorService.submit(new task()); } } } 執行結果:每隔2s左右打印2條信息 pool-1-thread-1完成 pool-1-thread-2完成 pool-1-thread-4完成 pool-1-thread-1完成 pool-1-thread-1完成 pool-1-thread-4完成 pool-1-thread-3完成 pool-1-thread-4完成 pool-1-thread-3完成 pool-1-thread-4完成 pool-1-thread-5完成 pool-1-thread-7完成 pool-1-thread-6完成 pool-1-thread-8完成 pool-1-thread-1完成 pool-1-thread-2完成
解析:咱們定義了一個許可數爲2的信號量,一次最多兩個線程同時執行,故執行結果是每隔2s左右打印2條信息。ui