【发布时间】:2018-06-05 22:42:08
【问题描述】:
我有一个场景,计算机与人类玩家玩井字游戏。用户在通过 Scanner obj 读取的控制台 (System.in) 上输入输入。在每一步之后,程序会决定是否有任何玩家可以做出让游戏更接近获胜的一步(获胜者可能是人类或计算机,没关系)。 我遇到的问题是,在程序决定游戏进入死胡同后(无论玩家采取什么行动,游戏都无法获胜),它会终止所有线程,除了等待用户的线程Scanner 对象上的输入。这导致我的程序挂起,直到用户输入某些内容。我想避免这种情况。 我的问题是:我可以在等待用户通过 inputStream 输入时关闭/终止线程吗? 我尝试以编程方式关闭扫描仪/底层 System.in 流/中断线程,但没有一个使线程脱离“等待用户输入”状态。
扫描仪:
private Scanner scanner = new Scanner(System.in);
人类玩家线程(在宣布获胜者或裁判判定没有玩家获胜时等待用户输入):
@Override
public void run() {
while (!Refree.isWinnerIdentified()) {
try {
System.out.println("Enter next cell location : ");
/*
while execution is waiting on below line for user inputs, all other threads sense that winner is identified and exit. This thread stays in limbo waiting for user inputs
*/
String location = scanner.nextLine();
//some other code...
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java multithreading java.util.scanner