我有以下代码
PlayerMove move;
Thread t = new Thread(new Timer());
t.start();
move = this.currentPlayer.GetPlayerMove();
如何在线程t终止后检查move变量是否为空?
答案 0 :(得分:1)
我的猜测是您想要的是这样的
CompletableFuture<PlayerMove> moveFuture = supplyAsync(currentPlayer::getPlayerMove);
try {
PlayerMove move = moveFuture.get(limit, TimeUnit.MILLISECONDS);
// player moved
} catch (TimeoutException e) {
// player did not move
}
CompletableFuture是一个表示结果的接口,该结果在单独的线程中进行计算(在这种情况下,是对currentPlayer.getPlayerMove()的调用)。您可以通过调用get()
来检索结果,该方法将永远等待或(在这种情况下)等待指定的时间。如果该超时时间已过,则会抛出TimeoutException
。