Java实现流控-Semaphore

来源:互联网 发布:数控机床编程技术 编辑:程序博客网 时间:2024/06/10 01:45

网上类似文章很多,不多说,直接上代码:

/** * 流控类(Semaphore实现) *  * @author ln * */public class FlowControl {/** * 最大访问量 */private static final int MAX_ACCESS_COUNT = 20;/** * 只能有MAX_ACCESS_COUNT个线程数同时访问 */private static final Semaphore semaphore = new Semaphore(MAX_ACCESS_COUNT);public static void main(String[] args) {// 线程池ExecutorService exec = Executors.newCachedThreadPool();// 模拟30个客户端for (int i = 0; i < 30; i++) {Runnable run = new Runnable() {@Overridepublic void run() {try {// 1秒钟内得不到许可,则丢弃访问。if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {System.out.println("正在执行...");//做一些事情...Thread.sleep(2 * 1000);System.out.println("执行完毕!");} else {System.out.println("访问被拒绝!!!");}} catch (InterruptedException e) {e.printStackTrace();} finally {// 执行完成,释放许可。semaphore.release();}}};exec.execute(run);}// 关闭线程池exec.shutdown();}}



原创粉丝点击