java - 控制并發(fā)線程數(shù)
問題描述
問題解答
回答1:如果你了解信號量的實現(xiàn)機(jī)制,那么這道題目也是一個意思。
public class Test { private final Integer maxCounter = 3; private Integer current = 0; public void call1() {//在這里補(bǔ)充代碼synchronized (this) { try {while (current.equals(maxCounter)) { // 請求 到達(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 秒鐘用于測試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)個線程在運(yùn)行。
回答2:用CountDownLatch。。。
相關(guān)文章:
1. mac里的docker如何命令行開啟呢?2. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?3. nignx - docker內(nèi)nginx 80端口被占用4. docker容器呢SSH為什么連不通呢?5. 關(guān)于docker下的nginx壓力測試6. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題7. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””8. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。9. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????10. docker-compose 為何找不到配置文件?

網(wǎng)公網(wǎng)安備