Java并发限流工具


/**
 * 
 * @author chichaofan
 *
 */
public class SimpleRateLimiter implements RateLimiter {

    private AtomicLong atomPermit;
    private long maxPermit;
    private long interval;
    private long lastTime;

    public SimpleRateLimiter(long permit, int intervalTime, TimeUnit t) {
        atomPermit = new AtomicLong(permit);
        interval = t.toNanos(intervalTime);
        maxPermit = permit;
    }

    @Override
    public void acquire(long tryPermit) {
        boolean rs = tryAcquire(tryPermit);
        if (rs)
            return;
         boolean  interrupted =false;
       try{
          long end = lastTime + interval;
        while (true) {
            try {
                NANOSECONDS.sleep((end - System.nanoTime()));
                rs = tryAcquire(tryPermit);
                if (rs)
                    return;
            } catch (InterruptedException e) {
                interrupted = true;
            }
        }
       }finally{
           if (interrupted) {
                Thread.currentThread().interrupt();
           }
       }

    }

    @Override
    public boolean tryAcquire(long tryPermit) {
        if (System.nanoTime() > (lastTime + interval)) {
            atomPermit.set(maxPermit);
            lastTime = System.nanoTime();
        }
        long value = atomPermit.get();
        boolean rs = false;
        while (value > 0 && !rs) {
            rs = atomPermit.compareAndSet(value, value - tryPermit);
            value = atomPermit.get();
        }
        return rs;
    }

    public static void main(String[] args) {
        final RateLimiter r = new SimpleRateLimiter(2, 1000, TimeUnit.MILLISECONDS);
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                     r.acquire(1);
                    System.out.println(Thread.currentThread().getName()+"true");
            }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                     r.acquire(1);
                    System.out.println(Thread.currentThread().getName()+"true");
            }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                     r.acquire(1);
                    System.out.println(Thread.currentThread().getName()+"true");
            }
            }
        }).start();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值