java - 控制并發(fā)線程數(shù)
問(wèn)題描述
問(wèn)題解答
回答1:如果你了解信號(hào)量的實(shí)現(xiàn)機(jī)制,那么這道題目也是一個(gè)意思。
public class Test { private final Integer maxCounter = 3; private Integer current = 0; public void call1() {//在這里補(bǔ)充代碼synchronized (this) { try {while (current.equals(maxCounter)) { // 請(qǐng)求 到達(dá)上限 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 秒鐘用于測(cè)試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();} }}
運(yùn)行這段代碼,你可以發(fā)現(xiàn)每 2 秒內(nèi),最多只有 3 (maxCounter)個(gè)線程在運(yùn)行。
回答2:用CountDownLatch。。。
相關(guān)文章:
1. python - 啟動(dòng)Eric6時(shí)報(bào)錯(cuò):’qscintilla_zh_CN’ could not be loaded2. php - 微信開(kāi)發(fā)驗(yàn)證服務(wù)器有效性3. MySQL中的enum類型有什么優(yōu)點(diǎn)?4. android下css3動(dòng)畫非常卡,GPU也不差啊5. mysql - 記得以前在哪里看過(guò)一個(gè)估算時(shí)間的網(wǎng)站6. css3 - 純css實(shí)現(xiàn)點(diǎn)擊特效7. javascript - 關(guān)于<a>元素與<input>元素的JS事件運(yùn)行問(wèn)題8. javascript - vue 怎么渲染自定義組件9. python - 有什么好的可以收集貨幣基金的資源?10. html - vue項(xiàng)目中用到了elementUI問(wèn)題
