久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

java - 控制并發線程數

瀏覽:134日期:2024-02-14 09:11:02

問題描述

問題解答

回答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。。。

標簽: java
相關文章:
主站蜘蛛池模板: 普兰县| 乡城县| 秦皇岛市| 繁昌县| 吉木乃县| 巢湖市| 垫江县| 永兴县| 福州市| 金塔县| 西吉县| 吴川市| 射阳县| 兴和县| 张掖市| 五常市| 玉屏| 德江县| 永清县| 日照市| 八宿县| 金坛市| 阳曲县| 黄平县| 项城市| 辽阳市| 台安县| 获嘉县| 大安市| 高邮市| 崇文区| 双桥区| 潮州市| 上犹县| 阜宁县| 邮箱| 康乐县| 皋兰县| 南部县| 罗田县| 绵阳市|