【完整代码】使用Semaphore实现限流代码示例

import java.util.concurrent.Semaphore;/**Semaphore信号量 基于AQS(内部维护了一个队列)可以用于限流 最多允许多少线程同时运行可以有很多个线程  但同时允许运行的线程有限制2个 new Semaphore(2)
*/
public class T11_TestSemaphore {public static void main(String[] args) {//允许一个线程同时执行// Semaphore s = new Semaphore(1);// 允许两个纤程同时执行Semaphore s = new Semaphore(2);//2 同时允许两个线程运行  true 公平与否 默认非公平// Semaphore s = new Semaphore(2, true);new Thread(()->{try {s.acquire();//获得许可 一共就2个许可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();}
}

在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部