Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java检查线程终止后的特定条件_Java_Multithreading - Fatal编程技术网

Java检查线程终止后的特定条件

Java检查线程终止后的特定条件,java,multithreading,Java,Multithreading,我有以下代码 PlayerMove move; Thread t = new Thread(new Timer()); t.start(); move = this.currentPlayer.GetPlayerMove(); 如何在线程t终止后检查move变量是否为null?我猜您想要的是这样的: CompletableFuture<PlayerMove> moveFuture = supplyAsync(currentPlayer::getPla

我有以下代码

    PlayerMove move;
    Thread t = new Thread(new Timer());
    t.start();
    move = this.currentPlayer.GetPlayerMove();

如何在线程t终止后检查move变量是否为null?

我猜您想要的是这样的:

CompletableFuture<PlayerMove> moveFuture = supplyAsync(currentPlayer::getPlayerMove);

try {
    PlayerMove move = moveFuture.get(limit, TimeUnit.MILLISECONDS);
    // player moved
} catch (TimeoutException e) {
    // player did not move
}

是一个接口,表示在单独线程中计算的结果。在本例中,是对currentPlayer.getPlayerMove的调用。您可以通过调用get来检索结果,get将永远等待,或者像在本例中一样,等待指定的一段时间。如果超时已过,将抛出TimeoutException。

不清楚您要求的是什么。您想知道如何检查线程是否结束吗?您想知道如何编写循环并等待该方法返回null结果吗?如果currentPlayer.GetPlayerMove直到线程结束后才返回null,则move可能永远不会为null,除非线程执行得太快,以至于它将在调用GetPlayerMove之前结束。除此之外,你还需要知道线程何时完成,有很多方法可以做到这一点,例如使用未来,加入线程等-你到底想实现什么?@GhostCat我想知道在计时器线程结束后移动变量是否为空。你是想给玩家在给定时间内移动的机会吗?@Thomas谢谢你的回答。我想要实现的是给玩家一个有限的移动时间,如果他/她不想,我想停止游戏。你能解释一下这个解决方案吗?@E.Omar在答案中添加了一个解释。