java控制每秒访问量

记录下java高并发控制每秒接口访问量



package test.thread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestSemaphore {
final static int MAX_QOS = 10;

private static int count = 0;
final static Semaphore semaphore = new Semaphore(MAX_QOS);
public static void main(String[] args) throws InterruptedException {
long startL = System.currentTimeMillis();
ScheduledExecutorService schePool = Executors.newScheduledThreadPool(1);
schePool.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
System.out.println("访问量:"+count);
count=0;
semaphore.release(MAX_QOS/3);
}

}, 1000, 1000, TimeUnit.MILLISECONDS);
ExecutorService pool = Executors.newFixedThreadPool(10);
for(int i=100;i>0;i--){
pool.submit(new Runnable(){
@Override
public void run() {
for(int j=10;j>0;j--){
semaphore.acquireUninterruptibly(1);
call();
}
}

});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.HOURS);
System.out.println("done cost:"+(System.currentTimeMillis()-startL)/1000);

}

public static synchronized void call(){
count++;
System.out.println(count);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值