约束每秒几个线程操作
RateLimiter limiter = RateLimiter.create(4.0);
示例
阻塞方式
limiter.acquire();
executor.submit(runnable);
条件方式
if(limiter.tryAcquire()){doSomething();
}else{//Boo can't get indoSomethingElse();
}
完整示例
import com.google.common.util.concurrent.RateLimiter;
import org.junit.Test;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;public class RateLimiterTest {@Testpublic void rateLimiterTest() throws Exception {final CountDownLatch waitSignal = new CountDownLatch(10);final ProtectedResource protectedResource = new ProtectedResource();Runnable expensiveThread = new Runnable() {@Overridepublic void run() {protectedResource.expensiveOperation();waitSignal.countDown();}};Executor executor = Executors.newFixedThreadPool(10);for (int i = 0; i <10; i++) {executor.execute(expensiveThread);}waitSignal.await();assertThat(waitSignal.getCount(),is(0L));}private class ProtectedResource {private RateLimiter rateLimiter = RateLimiter.create(2.0);public void expensiveOperation(){rateLimiter.acquire();System.out.println("Expensive operation run by "+Thread.currentThread()+" @ ["+new Date()+"]");}}
}