码上敲享录 > java高并发常见问题 > java如何限制并发数(semaphore)

java如何限制并发数(semaphore)

上一章章节目录下一章 2019-05-10已有1483人阅读 评论(0)

java如何限制并发数(semaphore)


解决方法:

以下代码限制最多只有10个线程可能会同时执行semaphore.acquire();和 semaphore.release();之间的代码,保证了cpu资源不被耗尽

package service;

import java.util.concurrent.Semaphore;

public class Test{

private Semaphore semaphore = new Semaphore(10);

public void test() {

try {

semaphore.acquire();

//业务代码开始

int sleepValue = ((int) (Math.random() *10000));

Thread.sleep(sleepValue);

//业务代码结束

semaphore.release();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交