Question

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!

Was it helpful?

Solution

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 !!!!");
    }
}

OTHER TIPS

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top