国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java - 控制并發(fā)線程數(shù)

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

問(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。。。

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 宁夏| 额敏县| 盐池县| 赤水市| 平利县| 习水县| 阿巴嘎旗| 巴彦淖尔市| 马公市| 巴林左旗| 大关县| 左权县| 尼勒克县| 友谊县| 芦山县| 肥城市| 东乌| 永宁县| 栾城县| 中西区| 华亭县| 黄龙县| 福安市| 赣州市| 于田县| 新郑市| 洛川县| 唐山市| 吉木萨尔县| 金坛市| 武冈市| 浦北县| 新闻| 葫芦岛市| 翁源县| 徐水县| 印江| 阳西县| 湖州市| 荔波县| 定陶县|