我正在创建一个多线程应用程序(如Typing Tutor游戏),其中给用户一些计时器(大约5秒),直到他必须在控制台中键入内容。在此超时之后我必须执行下一次迭代。
但阻塞调用如.read()
或.readLine()
阻塞直到用户输入(可能直到找到特定的分隔符)。
我可以从另一个线程中断这个Reader
线程吗?或者给我一些东西来实现这一点。
更新:代码
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
enum Dictionary
{
hippopotomus,syndrome,randomizer,typingtutor,hailstone
}
public class TypingTutorGame
{
static String word;
static String input = "";
static int generated;
static int accepted;
static Scanner s = new Scanner(System.in);
static boolean flag = false;
synchronized void generateWord() throws InterruptedException, IOException
{
while (flag)
{
wait(4000);
if (input.equals("*"))
{
return;
}
}
Random rnd = new Random();
int ordinal = rnd.nextInt(20);
Dictionary[] array = Dictionary.values();
word = array[ordinal].toString();
System.out.println(word);
generated++;
notify();
flag = true;
}
synchronized void inputWord() throws IOException
{
while (!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
input = "";
flag = false;
input = s.next();
if (input.equals(word))
{
accepted++;
}
notify();
}
@SuppressWarnings("unused")
public static void main(String[] args)
{
TypingTutorGame a = new TypingTutorGame();
WordDropper s = new WordDropper(a);
WordInput s2 = new WordInput(a);
}
}
class WordDropper extends TypingTutorGame implements Runnable
{
TypingTutorGame a;
Thread t1;
public WordDropper(TypingTutorGame a)
{
this.a = a;
t1 = new Thread(this);
t1.start();
}
@Override
public void run()
{
try
{
while (!input.equals("*"))
{
a.generateWord();
}
}
catch (InterruptedException | IOException e)
{
e.printStackTrace();
}
}
}
class WordInput extends TypingTutorGame implements Runnable
{
TypingTutorGame a;
Thread t;
public WordInput(TypingTutorGame a)
{
this.a = a;
t = new Thread(this, "Read");
t.start();
}
@Override
public void run()
{
while (!input.equals("*"))
{
try
{
a.inputWord();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (input.equals("*"))
{
System.out.println("Your score is" + accepted + "/" + (generated - 1));
s.close();
}
}
}
}