1

i want to print to console while waiting for input. Can this be done with multi-threading? If so, i dont know how to multi-thread. I need help!

3
  • Clarify your question. What do you mean by 'print to console while waiting for input'? Commented Mar 10, 2014 at 13:51
  • 'Yes' what? Explain with some pseudocode what you want and show what you have tried to achieve it! Commented Mar 10, 2014 at 13:56
  • @AlbertoSolano I want to print to the console while using the Scanner class to get input. Commented Mar 10, 2014 at 13:59

2 Answers 2

1

I am not sure if I understand your question but this is possible solution. There are two new threads created in main method. First read from console and write text back to it and second is only counting down from 50 to 0 and writing to console actual number:

public class App {
    public static void main(String[] args) {
        new Thread(new ReadRunnable()).start();
        new Thread(new PrintRunnable()).start();
    }
}

class ReadRunnable implements Runnable {

    @Override
    public void run() {
        final Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            final String line = in.nextLine();
            System.out.println("Input line: " + line);
            if ("end".equalsIgnoreCase(line)) {
                System.out.println("Ending one thread");
                break;
            }
        }
    }

}

class PrintRunnable implements Runnable {

    @Override
    public void run() {
        int i = 50;
        while(i>0) {
            System.out.println("Beep: " + i --);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                throw new IllegalStateException(ex);
            }
        }
        System.out.println("!!!! BOOM !!!!");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

use this code:

     public class KeyboardInput extends Thread{
        Scanner sc= new Scanner(System.in);
        @Override
        public void run()
        {
        while(true)
        {
        sc.hasNext();
        }

    }

}

Then just call this when you want to start the input:

Thread t1= new Thread(new KeyboardInput);
t1.start();

Now you have a thread that reads inputs while the main thread is free to print to screen

EDIT: be sure to only call the thread once!

1 Comment

Thread should not be directly inherited, implement Runnable instead and pass it as an argument of Thread's constructor like you attempted here. Furthermore, the second code snippet does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.