0

I am creating a multi-threaded application(like Typing Tutor game) where the user is given some timer(about 5 seconds) until which he has to type something in the console.After this timeout i have to perform next iteration.
But the blocking calls like .read() or .readLine() blocks until user input (and possibly until a specific delimiter is found).
Can i interrupt this Reader thread from another thread? Or give me something to achieve this.

Update:Code

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();

        }
    }

}

}
Shubham Kharde
  • 228
  • 2
  • 10

0 Answers0