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. windows誤人子弟啊2. php傳對應的id值為什么傳不了啊有木有大神會的看我下方截圖3. python - linux 下用wsgifunc 運行web.py該如何修改代碼4. python - oslo_config5. 關于mysql聯合查詢一對多的顯示結果問題6. 實現bing搜索工具urlAPI提交7. 冒昧問一下,我這php代碼哪里出錯了???8. mysql優化 - MySQL如何為配置表建立索引?9. MySQL主鍵沖突時的更新操作和替換操作在功能上有什么差別(如圖)10. 數據庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。
