java - 控制并发线程数
问题描述
问题解答
回答1:如果你了解信号量的实现机制,那么这道题目也是一个意思。
public class Test { private final Integer maxCounter = 3; private Integer current = 0; public void call1() {//在这里补充代码synchronized (this) { try {while (current.equals(maxCounter)) { // 请求 到达上限 wait();} } catch (InterruptedException ex) { } current++; notifyAll();}call2(current);synchronized (this) { try {while (current == 0) { wait();} } catch (InterruptedException ex) { } current--; notifyAll();} } private void call2(Integer current) {System.out.println(Thread.currentThread().getName() + ': I’m called ' + current);// 下面的休眠 2 秒钟用于测试try { Thread.sleep(2000);} catch (InterruptedException ex) { ex.printStackTrace(System.err);} } static class TestThread implements Runnable {private Test t;public TestThread(Test t) { this.t = t;}@Overridepublic void run() { t.call1();} } public static void main(String[] args) {Test t1 = new Test();TestThread tt = new TestThread(t1);for (int i = 0; i < 10; i++) { Thread t = new Thread(tt, 'Thread-' + i); t.start();} }}
运行这段代码,你可以发现每 2 秒内,最多只有 3 (maxCounter)个线程在运行。
回答2:用CountDownLatch。。。
相关文章:
1. java固定键值转换,使用枚举实现字典?2. vim - win10无法打开markdown编辑器3. mysql - 千万数据 分页,当偏移量 原来越大时,怎么优化速度4. 如何解决tp6在zend中无代码提示5. javascript - 有没有类似高铁管家的时间选择插件6. 这是什么情况???7. python - flask学习,user_syy添加报role is invalid keyword for User.8. css - BEM 中块(Block)有木有什么标准 何时决定一个部分提取为块而不是其父级的元素呢(Element)?~9. css3 - less或者scss 颜色计算的知识应该怎么学?或者在哪里学?10. javascript - 微信网页开发从菜单进入页面后,按返回键没有关闭浏览器而是刷新当前页面,求解决?
