天天看點

JUC之Semaphore-多線程與高并發

我們學習鎖的時候,當一個線程擷取到鎖,它才可以正常執行;未獲得鎖的線程阻塞。而Semaphore也相當于鎖,不過它可以定義鎖的數量,即同一時間可以控制讓多個線程都獲得鎖進而正常運作。

它控制同一時間點并發執行線程的個數。也可以控制某個資源可被同時通路的個數。主要用于限流。

用法就是一個acquire()方法用于獲得鎖,如果沒有獲得鎖則線程阻塞;另一個方法就是release()方法,線程執行完成後釋放鎖。

初始化時可以傳參指定控制并發的數量即鎖的數量。

Semaphore s = new Semaphore(2);
           
package com.mashibing.juc.c_020;

import java.util.concurrent.Semaphore;

public class T11_TestSemaphore {
    public static void main(String[] args) {
        //Semaphore s = new Semaphore(2);
        Semaphore s = new Semaphore(2, true);
        //允許一個線程同時執行
        //Semaphore s = new Semaphore(1);

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T1 running...");
                Thread.sleep(200);
                System.out.println("T1 running...");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                s.release();
            }
        }).start();

        new Thread(()->{
            try {
                s.acquire();

                System.out.println("T2 running...");
                Thread.sleep(200);
                System.out.println("T2 running...");

                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}