java - 控制并發(fā)線程數(shù)
問題描述
問題解答
回答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文檔怎么查看?2. android - NavigationView 的側(cè)滑菜單中如何保存新增項(xiàng)(通過程序添加)3. java - 怎么處理前臺(tái)要展示,但是數(shù)據(jù)庫(kù)表沒有該字段的實(shí)體類冗余屬性呢?4. javascript - ios返回不執(zhí)行js怎么解決?5. javascript - vue 元素加樣式該怎么做6. 除了 python2 和 python3,ipython notebook 還可以用哪些內(nèi)核?7. 這段代碼既不提示錯(cuò)誤也看不到結(jié)果,請(qǐng)老師明示錯(cuò)在哪里,謝謝!8. mysql - 怎么生成這個(gè)sql表?9. 提示語法錯(cuò)誤語法錯(cuò)誤: unexpected ’abstract’ (T_ABSTRACT)10. tp5 不同控制器中的變量調(diào)用問題
