首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CountDownLatch等待方法问题:不抛出超时

CountDownLatch等待方法问题:不抛出超时
EN

Stack Overflow用户
提问于 2021-08-19 04:44:39
回答 1查看 442关注 0票数 2

我正在编写一个简单的程序来演示CountDownLatch。这是我的节目:

代码语言:javascript
复制
class Players implements Runnable {
    private int delay;
    private String name;
    private CountDownLatch latch;

    Players(int delay, String name, CountDownLatch latch) {
        this.delay = delay;
        this.name = name;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println("Player" + name + "joined");
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }
}
代码语言:javascript
复制
public class LudoDemoUsingCountDownLatch {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(4);
        ExecutorService service = Executors.newFixedThreadPool(4);
        service.execute(new Players(11000, "player-1", latch));
        service.execute(new Players(12000, "player-2", latch));
        service.execute(new Players(13000, "player-3", latch));
        service.execute(new Players(14000, "player-4", latch));
        try {
            latch.await(1000, TimeUnit.MILLISECONDS);
            System.out.println("All four playesr joined. game started ");
        } catch (InterruptedException e) {
            System.out.println("cant start the game ");
        }
    }
}

我期望主线程应该在任何玩家加入之前就启动,并且在catch块中的代码应该执行,因为等待方法的等待时间小于所有玩家线程的睡眠方法。但我不能得到这个结果。相反,它显示了所有的玩家都加入了,游戏开始了:

产出:

代码语言:javascript
复制
 1. Player-2joined
 2. Player-3joined
 3. Player-1joined
 4. Player-4joined
 5. All four players joined. game started 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-19 05:22:39

您需要检查CountDownLatch.await的返回值。它不会在超时时抛出InterruptedException,而是返回false

因此,您的main方法的更正版本如下所示:

代码语言:javascript
复制
CountDownLatch latch = new CountDownLatch(4);
ExecutorService service = Executors.newFixedThreadPool(4);
service.execute(new Players(11000, "player-1", latch));
service.execute(new Players(12000, "player-2", latch));
service.execute(new Players(13000, "player-3", latch));
service.execute(new Players(14000, "player-4", latch));
boolean started = false;
try {
    started = latch.await(1000, TimeUnit.MILLISECONDS);
    if (started) {
        System.out.println("All four players joined. game started ");
    }
} catch (InterruptedException e) {
    System.out.println("Interrupted - won't generally be hit");
}
if (!started) {
    System.out.println("Can't start the game");
}

请注意,您可能还打算将System.out.println("Player" + name + "joined");放在Player中的Thread.sleep调用之后。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68842160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档