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. mysql如何配置遠(yuǎn)程php外網(wǎng)鏈接數(shù)據(jù)庫(kù)2. 老師 我是一個(gè)沒(méi)有學(xué)過(guò)php語(yǔ)言的準(zhǔn)畢業(yè)生 我希望您能幫我一下3. mysql - eclispe無(wú)法打開數(shù)據(jù)庫(kù)連接4. mysql 5萬(wàn)張表 導(dǎo)出成sql 不要內(nèi)容,只要結(jié)構(gòu),非常慢。如何解決啊?5. 導(dǎo)入數(shù)據(jù)庫(kù)不成功6. 數(shù)據(jù)庫(kù) - mysql中有沒(méi)查看數(shù)據(jù)大小的函數(shù)??7. PHP單例模式8. mysql如何判斷數(shù)據(jù)不存在則插入呢?9. mysql - 關(guān)于數(shù)據(jù)緩存策略方面的疑惑10. mysql無(wú)法刪除字段(錯(cuò)誤1091),但是對(duì)該字段設(shè)置主鍵后就可刪除,為什么?
