Java多線程工具箱之Semaphore

Java多線程工具箱之Semaphore

前言

這一篇談一下Semaphore:信號量。java

將Semaphore類比爲爲信號燈,被繼承Runable的線程類比爲列車:理解信號量能夠參考控制列車的信號燈:鐵道上有多個列車,由信號燈通知其可用狀況。若列車拿到的信號燈爲綠燈,列車能夠經過,不然列車不能經過。shell

Semaphore用於限制訪問線程多於可用資源的場景。多線程

1.1 基本API

構造器 Semaphore(int premits)

構造傳入初始化的容許數量。dom

方法 acquire()

請求容許,未有有效的容許或者中斷以前,線程將會阻塞。ide

方法 release()

釋放容許。工具

1.2 範例

在範例中,咱們使用一個機場請求跑道的模擬程序,機場有3個跑道,這個時段降落的航班一共有10個。因爲跑道遠沒有飛機的數量多,所以須要飛機須要等待可用的跑道資源。這個程序就是模擬了這個過程。ui

UML

SoWkIImgAStDuNBEIImkLd0iA82nCeiAyejA4Bo0dCIyL2Wtg3IlFB6IopMlD5V1CRaaCp-FYmkeLI5VLpSdDQr4rmwc7IPQb9cU0HH6c0EL1ydPGOrJi5B8I2pcWYbHqDEhGP8gBSxCIuTBWlN1h7P8pKi1UW40

App.java

import java.util.Random;

import lombok.extern.java.Log;

@Log
public class App {

    static Random ran = new Random(System.currentTimeMillis());

    public static void main(String[] args) {
        Airport ap = new Airport("Baiyun Airport", 3);
        for (int index = 0; index < 10; index++) {

            AirPlane plane = new AirPlane(index, String.valueOf(index), String.valueOf(index), ap,
                    ran.nextInt(2) == 0 ? Action.landing : Action.takeOff);
            Thread thread = new Thread(plane);
            thread.start();
        }
    }

}
Airport.java
import java.util.Arrays;
import java.util.concurrent.Semaphore;

import lombok.Data;
import lombok.extern.java.Log;

@Log
@Data
public class Airport {

    private String name;
    private Semaphore semaphore;
    private Runway[] runways;

    public Airport(String name, int numberOfRunway) {

        this.name = name;
        this.semaphore = new Semaphore(numberOfRunway);
        runways = new Runway[numberOfRunway];

        for (int index = 0; index < numberOfRunway; index++) {
            Runway currentRunway = new Runway(name, index);

            runways[index] = currentRunway;
        }

        log.info("Airpot is ready :" + Arrays.toString(runways));

    }

    public Runway requestRunway() throws InterruptedException {
        semaphore.acquire();

        while (true) {
            for (int index = 0; index < runways.length; index++) {
                Runway runway = runways[index];
                if (!runway.isInUse()) {
                    runway.setInUse(true);
                    return runway;
                }
            }
            log.warning("all runway is using, and wait till there is runay release.");
        }
    }

    public void releaseRunway(Runway release) {

        for (int index = 0; index < runways.length; index++) {
            Runway runway = runways[index];
            if (runway.equals(release)) {
                runway.setInUse(false);
                semaphore.release();
            }
        }

    }

}

Airplane.java

import java.util.Random;

import lombok.Data;
import lombok.extern.java.Log;

@Data
@Log
public class AirPlane implements Runnable {

    private int id;
    private String name;
    private String company;
    private Airport airport;
    private Action action;
    private static Random rand = new Random(System.currentTimeMillis());

    public AirPlane(int id, String name, String company, Airport airport, Action action) {
        this.id = id;
        this.name = name;
        this.company = company;
        this.airport = airport;
        this.action = action;
    }

    @Override
    public void run() {

        Runway runway = null;

        try {
            runway = airport.requestRunway();

            log.info(this.toString() + "is using " + runway.toString() + " to " + this.action);

            int sleepSecond = rand.nextInt(10) * 1000;

            Thread.sleep(sleepSecond);

        } catch (InterruptedException e) {
            log.warning("request runway error");
            e.printStackTrace();
        } finally {

            if (airport != null && runway != null) {
                airport.releaseRunway(runway);
            }
        }

    }

}

Runway.java

import lombok.Data;

@Data
public class Runway {

    private String name;
    private boolean inUse = false;

    public Runway(String airportName, int runwayIndex) {
        this.name = airportName + "_" + runwayIndex;
    }

}

運行結果

能夠從運行結果中看到,程序運行的第一秒,首先幾架的飛機(線程)都第一時間的得到了跑道(資源),然後面幾架飛機(線程),則在前面的飛機退出(sleep)跑道(資源)後得到使用權,進行起飛或降落。this

Aug 13, 2018 12:56:32 AM online.tangbk.thread.study.semaphore.Airport <init>
信息: Airpot is ready :[Runway(name=Baiyun Airport_0, inUse=false), Runway(name=Baiyun Airport_1, inUse=false), Runway(name=Baiyun Airport_2, inUse=false)]
Aug 13, 2018 12:56:33 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=1, name=1, company=1, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 1], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=false)]), action=landing)is using Runway(name=Baiyun Airport_1, inUse=true) to landing
Aug 13, 2018 12:56:33 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=2, name=2, company=2, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=takeOff)is using Runway(name=Baiyun Airport_2, inUse=true) to takeOff
Aug 13, 2018 12:56:33 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=0, name=0, company=0, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 2], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=false), Runway(name=Baiyun Airport_2, inUse=false)]), action=landing)is using Runway(name=Baiyun Airport_0, inUse=true) to landing
Aug 13, 2018 12:56:33 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=8, name=8, company=8, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=takeOff)is using Runway(name=Baiyun Airport_1, inUse=true) to takeOff
Aug 13, 2018 12:56:35 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=3, name=3, company=3, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=takeOff)is using Runway(name=Baiyun Airport_0, inUse=true) to takeOff
Aug 13, 2018 12:56:37 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=4, name=4, company=4, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=landing)is using Runway(name=Baiyun Airport_2, inUse=true) to landing
Aug 13, 2018 12:56:40 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=5, name=5, company=5, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=landing)is using Runway(name=Baiyun Airport_2, inUse=true) to landing
Aug 13, 2018 12:56:40 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=6, name=6, company=6, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=landing)is using Runway(name=Baiyun Airport_2, inUse=true) to landing
Aug 13, 2018 12:56:41 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=7, name=7, company=7, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=takeOff)is using Runway(name=Baiyun Airport_1, inUse=true) to takeOff
Aug 13, 2018 12:56:41 AM online.tangbk.thread.study.semaphore.AirPlane run
信息: AirPlane(id=9, name=9, company=9, airport=Airport(name=Baiyun Airport, semaphore=java.util.concurrent.Semaphore@61a09c6b[Permits = 0], runways=[Runway(name=Baiyun Airport_0, inUse=true), Runway(name=Baiyun Airport_1, inUse=true), Runway(name=Baiyun Airport_2, inUse=true)]), action=landing)is using Runway(name=Baiyun Airport_0, inUse=true) to landing

1.3 Semaphore小結

Semaphore適用於多線程請求數量資源的場景,但沒法解決單多個線程對同一資源訪問的競爭性訪問。對於單一資源的競爭性訪問,依然要使用synchronize關鍵字或atomic等甚至ReadWriteLock關鍵字或工具類進行限制。
在後面咱們在咱們的多線程工具箱裏面陸續會提到。atom

相關文章
相關標籤/搜索