java semaphore 信号量,流控程序

时间:2021-09-28 04:37:06

信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。 

Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。


import java.util.Date;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

import java.util.concurrent.TimeUnit;

public class Test {

final static int MAX_QPS = 10;

final static Semaphore semaphore = new Semaphore(MAX_QPS);

public static void main (String ... args) throws Exception {

Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {

@Override

public void run() {

semaphore.release(MAX_QPS/2);

}

}, 1000, 500, TimeUnit.MILLISECONDS);

//lots of concurrent calls:100 * 1000
ExecutorService pool = Executors.newFixedThreadPool(100);

for (int i=100;i>0;i--) {

final int x = i;

pool.submit(new Runnable() {

@Override

public void run() {

for (int j=1000;j>0;j--) {

semaphore.acquireUninterruptibly(1);
remoteCall(x, j);

}

}

});

}

pool.shutdown();

pool.awaitTermination(1, TimeUnit.HOURS);

System.out.println("DONE");
}

private static void remoteCall(int i, int j) {
System.out.println(String.format("%s - %s: %d %d",new Date(),
Thread.currentThread(), i, j));
}

}

转自:http://ifeve.com/concurrency-practice-1/