【完整代码】使用Semaphore实现限流代码示例
生活随笔
收集整理的這篇文章主要介紹了
【完整代码】使用Semaphore实现限流代码示例
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import java.util.concurrent.Semaphore;/**Semaphore信號量 基于AQS(內(nèi)部維護(hù)了一個(gè)隊(duì)列)可以用于限流 最多允許多少線程同時(shí)運(yùn)行可以有很多個(gè)線程 但同時(shí)允許運(yùn)行的線程有限制2個(gè) new Semaphore(2)
*/
public class T11_TestSemaphore {public static void main(String[] args) {//允許一個(gè)線程同時(shí)執(zhí)行// Semaphore s = new Semaphore(1);// 允許兩個(gè)纖程同時(shí)執(zhí)行Semaphore s = new Semaphore(2);//2 同時(shí)允許兩個(gè)線程運(yùn)行 true 公平與否 默認(rèn)非公平// Semaphore s = new Semaphore(2, true);new Thread(()->{try {s.acquire();//獲得許可 一共就2個(gè)許可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...");} catch (InterruptedException e) {e.printStackTrace();} finally {s.release();}}).start();}
}
總結(jié)
以上是生活随笔為你收集整理的【完整代码】使用Semaphore实现限流代码示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 详解各种锁:CAS、共享锁、排它锁、互斥
- 下一篇: 【完整代码】使用Semaphore实现线