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. mysql - 在不允許改動數據表的情況下,如何優化以varchar格式存儲的時間的比較?2. css - chrome下a標簽嵌套img 顯示會多個小箭頭?3. css3 - 純css實現點擊特效4. docker網絡端口映射,沒有方便點的操作方法么?5. java中返回一個對象,和輸出對像的值,意義在哪兒6. mysql 為什么主鍵 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?7. vim - docker中新的ubuntu12.04鏡像,運行vi提示,找不到命名.8. javascript - 有適合開發手機端Html5網頁小游戲的前端框架嗎?9. javascript - Img.complete和img.onload判斷圖片加載完成有什么區別?10. 推薦好用mysql管理工具?for mac和pc
