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. angular.js - 不适用其他构建工具,怎么搭建angular1项目2. python如何不改动文件的情况下修改文件的 修改日期3. mysql - 一个表和多个表是多对多的关系,该怎么设计4. javascript - git clone 下来的项目 想在本地运行 npm run install 报错5. mysql主从 - 请教下mysql 主动-被动模式的双主配置 和 主从配置在应用上有什么区别?6. android-studio - Android 动态壁纸LayoutParams问题7. 主从备份 - 跪求mysql 高可用主从方案8. angular.js - 三大框架react、vue、angular的分析9. python 如何实现PHP替换图片 链接10. python - django 里自定义的 login 方法,如何使用 login_required()
